五個迭代方法 都接受兩個參數(shù):要在每一項上運行的函數(shù) 和 運行該函數(shù)的作用域(可選)
every():對數(shù)組中的每一項運行給定函數(shù)。如果函數(shù)對每一項都返回true,則返回true。
filter():對數(shù)組中的每一項運行給定函數(shù)。返回該函數(shù)會返回true的項組成的數(shù)組。
forEach():對數(shù)組中每一項運行給定函數(shù)。該函數(shù)沒有返回值。
map():對數(shù)組中每一項運行給定函數(shù)。返回每次函數(shù)調(diào)用的結(jié)果組成的函數(shù)。
some():對數(shù)組中每一項運行給定函數(shù)。如果函數(shù)對 任一項返回true,則返回true
復(fù)制代碼代碼如下:
var numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
//every()和some()最相似
//every() item:當(dāng)前遍歷項,index:當(dāng)前項索引,array:數(shù)組對象本身
var everyResult = numbers.every(function (item, index, array) {
return item > 2;
});
alert(everyResult);//false
//some()
var someResult = numbers.some(function (item, index, array) {
return item > 2;
});
alert(someResult);//true
//filter
var filterResult = numbers.filter(function (item, index, array) {
return item > 2;
});
alert(filterResult);//[3,4,5,4,3]
//map()
var mapResult = numbers.map(function (item, index, array) {
return (item * 2);
});
alert(mapResult);//[2,4,6,8,10,8,6,4,2]
//forEach 本質(zhì)上和for循環(huán)沒有區(qū)別
var forEachResult=numbers.forEach(function(item,index,array){
alert(item)
});
以上就是本文的全部內(nèi)容了,希望能給大家一些提示,能夠更好的理解javascript迭代方法。