遍历数组的几种方法

127 阅读1分钟

forEach

// eg:
var arr = ['a', 'b', 'c', 'd'];
arr.forEach(function(value, index) {
  console.log('value=', value, 'index=', index);
})


// 输出:
// value= a  index= 0
// value= b  index= 1
// value= c  index= 2
// value= d  index= 3

map

可以对遍历的每一项做相应的处理,返回每次函数调用的结果组成的新数组

eg:
var arr = ['a', 'b', 'c', 'd'];
arr.map(function(item, index, array) {
  console.log(item, index);
})


// 输出:
// a 0
// b 1
// c 2
// d 3

for in(不推荐)

因为数组也是对象,所以适用对象遍历的for in方法。但是不仅会遍历数字键,还会遍历非数字键,本质上是遍历对象自身和原型链上除Symbol外的所有可枚举属性。所以不推荐使用这种方法来遍历数组。

// eg:
var arr = ['a', 'b', 'c', 'd'];
for (var i in arr) {
  console.log('index:', i, 'value:', arr[i])
}

// 输出:
// index= 0 value= a
// index= 1 value= b
// index= 2 value= c
// index= 3 value= d

for of

只遍历出value,不能遍历出下标,可遍历出Symbol数据类型的属性,此方法可以遍历所有可迭代对象

// eg:
var arr = ['a', 'b', 'c', 'd'];
for (var value of arr) {
  console.log('value', value)
}

// 输出:
// value= a
// value= b
// value= c
// value= d