ES6和js的遍历方法

14 篇文章 0 订阅

遍历

  • ES6提供了三个新方法—entries(), keys(),和values()。这些方法都是用于遍历数组,都返回一个遍历器对象。可用for…of 循环遍历,唯一的区别在于,keys(),是对键名的遍历,values()是对键值的遍历,entries()是对键值对的遍历。
//keys()方法
for(let index of ['a''b'].keys()){
     console,log(index);       //输出 0 1
     }
//values()方法
for(let elem of ['a''b'].values()){
     console.log(elem);        //输出‘a’  'b'
  }
//entries()方法
for(let [index,elem] of ['a''b'].entries()){
     console.log(index,elem)//输出0 “a”  1 "b"
}

如果不使用for…of循环,可以手动调用遍历器对象的next方法进行遍历

let letter = ['a''b',’c‘];
let entries = letter.entries();
console.log(entries.next().value);   //[0,'a']
console.log(entries.next().value);   //[1,'b']
console.log(entries.next().value);   //[2,'c']
  • js(ES5)的遍历方法:ES5为数组定义了5个迭代方法,每个方法都接收两个参数:要在每一项上运行的函数和(可选的)运行该函数的作用域位置—影响this的值。传入这些方法中的函数会接收三个参数:数组项的值,该项在数组中的位置和数组对象本身。根据使用的方法的不同,函数的执行结果是不一样的。

  • every():对数组中的每一项运行给定的函数,如果该函数对每一项都返回true,则返回true

  • filter(): 对数组中的每一项运行给定的函数,返回该函数会返回true的项组成的数组

  • forEach():对数组中的每一项运行给定的函数,这个函数没有返回值

  • map():对数组中的每一项运行给定的函数,返回每次函数调用的结果组成的数组

  • some():对数组中的每一项运行给定的函数,如果该函数对任一项返回true,则返回true
    以上的方法都不会修改数组中的包含的值

var numbers = [1,2,3,4,5,4,3,2,1];
var everyResult = numbers.every(function (item, index, array){
   return (item > 2);
})
 alert(everyResult);      //false


var someResult = numbers .some(function (item , index ,array){
   return (item >2);
})
alert(someResult);      //true

var filterResult = numbers .filter(function (item , index ,array){
   return (item>2);
})
alert(filterResult);    [3,4,5,4,3]

var mapResult = numbers .map(function (item ,index ,array){
   return item *2;
})
alert(mapResult);     [2,4,6,8,10,8,6,4,2]

numbers.forEach(function (item ,index,array){
   //执行某些操作
})
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值