js数组中的遍历


转载
作者: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 infor of是遍历对象时使用的,一般不推荐用来遍历数组。 
3. for in 用来遍历对象的键名,for of 用来遍历对象的键值。
4. forEach方法一般不返回值,只用来操作数据,会跳过空位。
5. map方法返回一个新数组,会跳过空位。
6. filter方法返回一个新数组,用来根据条件过滤数组的,会跳过空位。
7. es6的三种方法都返回一个遍历器对象,可以用for...of循环进行遍历, keys()是对键名的遍历、values()是对键值的遍历,entries()是对键值对的遍历。它们都不会跳过空位。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值