前言
Array 数组遍历的几种方式
普通for循环
循环遍历基础语法
for(var i = 0; i < arr.length; i++){
...
}
使用示例
var arr1 = ['hello', 'world', 'aa'];
for (var i=0; i<arr1.length; i++){
console.log(i) // 下标
console.log(arr1[i]) // 成员
}
运行结果
for...in
for...in
循环的是数组下标,语法结构
for(var index in arr){
...
}
示例
var arr1 = ['hello', 'world', 'aa'];
for (var index in arr1){
console.log(index); // 下标
console.log(arr1[index])
}
运行结果
for...of
for...of
循环的是数字成员,语法结构
for(var item of arr){
...
}
使用示例
var arr1 = ['hello', 'world', 'aa'];
for(var item of arr1){
console.log(item) // 成员
}
forEach
forEach 只有数组对象才有此方法, forEach() 方法用于调用数组的每个元素,并将元素传递给回调函数。
注意: forEach() 对于空数组是不会执行回调函数的。
array.forEach(function(currentValue, index, arr), thisValue)
forEach() 中可以传2个参数,其中function(currentValue, index, arr)
是必需。 数组中每个元素需要调用的函数。
function 参数 | 说明 |
---|---|
currentValue | 必需。当前元素 |
index | 可选。当前元素的索引值。 |
arr | 可选。当前元素所属的数组对象。 |
基础语法结果
var arr1 = ['hello', 'world', 'aa'];
arrObj.forEach(function(item, index, obj){
// item 遍历出的每一个元素
// index 元素对应的下标
// obj 数组本身
})
使用示例
var arr1 = ['hello', 'world', 'aa'];
arr1.forEach(function(item, index, obj){
console.log(item) // item 遍历出的每一个元素
console.log(index) // index 元素对应的下标
console.log(obj) // obj 数组本身
console.log(obj.length) // obj 数组本身
})
其中thisValue是可选。它表示传递给函数的值一般用 "this" 值。当没有thisValue 参数时,在函数内部this指的是window对象
var arr1 = ['hello', 'world', 'aa'];
person = {
name: 'yoyo',
age: 22,
words: function () {
arr1.forEach(function (item) {
console.log(this) // window
})
}
}
person.words();
此时this指的是window对象
forEach传第二个参数thisValue是时, this才会指向外面的person对象
var arr1 = ['hello', 'world', 'aa'];
person = {
name: 'yoyo',
age: 22,
words: function () {
arr1.forEach(function (item) {
console.log(this) // window
})
},
info: function () {
arr1.forEach(function (item) {
console.log(this) // person
}, this)
}
}
person.words();
person.info();
遍历数组有很多方法,以上四种最常用,其中forEach是只有数组中才有的方法。