es5瀏覽器兼容:
- Opera 11+
- Firefox 3.6+
- Safari 5+
- Chrome 8+
- Internet Explorer 9+
es5 為數(shù)組定義了5 個迭代方法椭懊。每個方法都接收兩個參數(shù):要在每一項上運行的函數(shù)和(可選的)運行該函數(shù)的作用域?qū)ο蟆绊憈his 的值。傳入這些方法中的函數(shù)會接收三個參數(shù):數(shù)組項的值、該項在數(shù)組中的位置和數(shù)組對象本身蹋嵌。根據(jù)使用的方法不同绞铃,這個函數(shù)執(zhí)行后的返回值可能會也可能不會影響方法的返回值袋励。以下是這5 個迭代方法的作用乙嘀。 - every():對數(shù)組中的每一項運行給定函數(shù)显蝌,如果該函數(shù)對每一項都返回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
- filter():對數(shù)組中的每一項運行給定函數(shù),返回該函數(shù)會返回true 的項組成的數(shù)組酬诀。
var numbers = [1,2,3,4,5,4,3,2,1];
var filterResult = numbers.filter(function(item, index, array){
return (item > 2);
});
alert(filterResult); //[3,4,5,4,3]
- forEach():對數(shù)組中的每一項運行給定函數(shù)脏嚷。這個方法沒有返回值。
var numbers = [1,2,3,4,5,4,3,2,1];
.numbers.forEach(function(item, index, array){
//執(zhí)行某些操作
});
//它只是對數(shù)組中的每一項運行傳入的函數(shù)料滥。這個方法沒有返回值然眼,本質(zhì)上與使用for 循環(huán)迭代數(shù)組一樣。
- map():對數(shù)組中的每一項運行給定函數(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;
});
alert(mapResult); //[2,4,6,8,10,8,6,4,2]
- some():對數(shù)組中的每一項運行給定函數(shù),如果該函數(shù)對任一項返回true践宴,則返回true鲸匿。
var numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
var someResult = numbers.some(function(item, index, array) {
return (item > 2);
});
alert(someResult); //true
以上方法都不會修改數(shù)組中的包含的值。