转载
作者:tiancai啊呆
地址:http://www.jianshu.com/p/ab88f5efd928
说明:以下方法均已验证(自己重敲了一遍)
定义一个数组:
let arr = ['a','b','c','',,'d'];
- 常规方法
for (let i = 0; i< arr.length; i++) {
console.log(i);
//输出:0,1,2,3,4,5
console.log(arr[i]);
//输出:a b c undefined d c后面是空
}
- for in
for(let i in arr){
console.log(i);
//输出:0,1,2,3,4,5
console.log(arr[i]);
//输出:a b c undefined d c后面是空
}
- for of
for (var i of arr) {
console.log(i);
//输出:a b c undefined d c后面是空
}
- 数组实例的forEach方法
arr.forEach(function(value){
console.log(value);
//输出:a b c d c后面是空
})
- 数组实例的map方法
arr.map(function(value){
console.log(value);
//输出:a b c d c后面是空
})
- 数组实例的filter方法
arr.filter(function(value){
console.log(value);
//输出:a b c d c后面是空
})
- es6的keys方法
for (let index of arr.keys()) {
console.log(index);
//输出:0,1,2,3,4,5
}
- es6的values方法
for (let elem of arr.values()) {
console.log(elem);
//输出:输出错误arr.values is not a function
}
- es6的entries方法
for (let [index, elem] of arr.entries()) {
console.log(index,elem);
//输出:0 "a",1 "b",2 "c",3 "",4 undefined,5 "d"
}
1. 最常见也是使用最广的就是普通的for循环,它适用所有的遍历场景,不会跳过空位。
2. for in 与for of是遍历对象时使用的,一般不推荐用来遍历数组。
3. for in 用来遍历对象的键名,for of 用来遍历对象的键值。
4. forEach方法一般不返回值,只用来操作数据,会跳过空位。
5. map方法返回一个新数组,会跳过空位。
6. filter方法返回一个新数组,用来根据条件过滤数组的,会跳过空位。
7. es6的三种方法都返回一个遍历器对象,可以用for...of循环进行遍历, keys()是对键名的遍历、values()是对键值的遍历,entries()是对键值对的遍历。它们都不会跳过空位。