js循環/迭代/遍歷有多少方法
JavaScript中存在着很多循環的方法
常見的有for,while,do while,for in等,
ES5中的forEach,
ES6的for of ,
jquery中封裝的each
for
局限性很大,通過累加數組索引,來輸出數組中的值。一般用來遍歷數組,不能遍歷對象,因為對象的長度是undefined,無法作為其循環的條件。
let person = {
name1:"fur",
age:"1",
hobbies:{
study:"code",
play:"games"
}
}
let arr = ['fur','furfur','furfur-jiang']
console.log("遍歷對象結果:")
console.log("person對象長度= "+person.length)
console.log("遍歷數組結果:")
for(let i = 0 ; i < arr.length ; i++){
console.log(arr[i])
}
for - 循環代碼塊一定的次數
while - 當指定的條件為 true 時循環指定的代碼塊
do/while - 同樣當指定的條件為 true 時循環指定的代碼塊
for…in
for…in 循環將遍歷對象的所有可枚舉屬性。不但可以循環遍歷數組,還可以循環遍歷對象。
for (let index in Object) {
//
}
let person = {
name1:"fur",
age:"1",
hobbies:{
study:"code",
play:"games"
}
}
let arr = ['fur','furfur','furfur-jiang']
//遍歷對象
console.log("遍歷對象結果:")
for (let i in person) {
if(person[i] instanceof Object){
for (let j in person[i]){
console.log(person[i][j])
}
}else{
console.log(person[i])
}
}
//遍歷數組
console.log("遍歷數組結果:")
for (let i in arr) {
console.log(arr[i])
}
forEach
forEach() 方法用於調用數組的每個元素,並將元素傳遞給回調函數。可通過參數直接獲取到值,其中item為該索引下的值,index為索引,arr為數組本身,參數名可改變,但是順序不能改變。
注意:
-
forEach() 對於空數組是不會執行回調函數的。
-
不能遍歷對象
array.forEach(function(item, index, arr), thisValue)
參數 | 描述 |
---|---|
currentValue | 必需。當前元素 |
index | 可選。當前元素的索引值。 |
arr | 可選。當前元素所屬的數組對象。 |
let arr = ['fur','furfur','furfur-jiang']
//遍歷數組
console.log("遍歷數組結果:")
arr.forEach(function(item, index, arr){
console.log(item)
console.log(index)
console.log(arr)
})
for of
for...of
語句創建一個循環來迭代可迭代的對象。ES6新增的方法,但是缺點是無法遍歷自定義普通對象。
for...of
允許你遍歷 Arrays(數組), Strings(字符串), Maps(映射), Sets(集合),TypedArray,函數的 arguments 對象,NodeList 對象等可迭代的數據結構等。
語法
for (variable of iterable) {
statement
}
- variable:每個迭代的屬性值被分配給該變量。
- iterable:一個具有可枚舉屬性並且可以迭代的對象。
let arr = ['fur','furfur','furfur-jiang']
//遍歷數組
console.log("遍歷數組結果:")
for (let item of arr){
console.log(item)
}
Set 和 Map 結構
Set 結構遍歷時,返回的是一個值,而 Map 結構遍歷時,返回的是一個數組,該數組的兩個成員分別為當前 Map 成員的鍵名和鍵值。
let map = new Map()
map.set("name1","fur")
map.set("name2","furfur")
map.set("name3","furfur-jiang")
// 也可以這樣鏈式定義
//let map = new Map().set("name1","fur").set("name2","furfur").set("name3","furfur-jiang")
console.log("Set結構遍歷:")
for(let [key,value] of map) {
console.log(key +'.'+ value)
}
console.log("Map結構遍歷:")
for(let i of map){
console.log(i)
}
each循環
jquery下的each方法有兩種:
-
一種為$(’ ').each(),是搭配jq選擇器遍歷jquery對象獲取頁面元素的方法。
-
一種為$.each()循環方法,用於循環遍歷數組、對象。
注意:用這個方法需要導入jq的包,each與forEach的item和index放置位置相反哦!
let person = {
name1:"fur",
age:"1",
hobbies:{
study:"code",
play:"games"
}
}
let arr = ['fur','furfur','furfur-jiang']
//遍歷對象
console.log("遍歷對象結果:")
$.each(person,function(index,item){
if(item instanceof Object){
$.each(item,function(index,item){
console.log(index+'.'+item)
})
}else{
console.log(index+'.'+item)
}
})
//遍歷數組
console.log("遍歷數組結果:")
$.each(arr,function(index,item){
console.log(index+'.'+item)
})
碼字不易,有用的話點個贊呀!謝謝