遍历
- 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){
//执行某些操作
})