ES5為數(shù)組定義了5個(gè)迭代的方法蜡励。每個(gè)方法都接收兩個(gè)參數(shù):
要在每一項(xiàng)上運(yùn)行的函數(shù)
運(yùn)行該函數(shù)的作用域?qū)ο?-影響this的值 可選
運(yùn)行的函數(shù)會(huì)接受三個(gè)參數(shù):1.數(shù)組項(xiàng)的值 2.該項(xiàng)在數(shù)組中的位置 3.數(shù)組對(duì)象本身初茶。
·every()
對(duì)數(shù)組的每一項(xiàng)運(yùn)行給定函數(shù)颗管,如果該函數(shù)對(duì)每一項(xiàng)都返回true蒲犬,則返回true鸦采。
var numbers = [1,2,3,4,5,4,3,2,1];
var everyResult = numbers.every(function(item,index,array){
return (item > 2);
})
console.log(everyResult); //false
·some()
對(duì)數(shù)組的每一項(xiàng)運(yùn)行給定函數(shù)饱岸,如果該函數(shù)對(duì)任一項(xiàng)返回true屡久,則返回true
var numbers = [1,2,3,4,5,4,3,2,1];
var someResult = numbers.some(function(item,index,array){
return (item > 2);
})
console.log(someResult); //true
·filter()
對(duì)數(shù)組的每一項(xiàng)運(yùn)行給定函數(shù)看杭,返回每次函數(shù)調(diào)用的結(jié)果組成的數(shù)組
var numbers = [1,2,3,4,5,4,3,2,1];
var mapResult = numbers.map(function(item,index,array){
return item*2;
})
console.log(mapResult); //[2,4,6,8,10,8,6,4,2]
·forEach()
對(duì)數(shù)組的每一項(xiàng)運(yùn)行給定函數(shù)耍贾,返回該函數(shù)會(huì)返回true的項(xiàng)組成的數(shù)組
var numbers = [1,2,3,4,5,4,3,2,1];
var filterResult = numbers.filter(function(item,index,array){
return (item > 2);
})
console.log(filterResult); //[3,4,5,4,3]
·map()
對(duì)數(shù)組的每一項(xiàng)運(yùn)行給定函數(shù)阅爽。該方法沒(méi)有返回值
var numbers = [1,2,3,4,5,4,3,2,1];
numbers.forEach(function(item,index,array){
console.log(item); //代碼塊
})