常見數組迭代方法:前端
數組
map 返回 每次函數調用返回的結果 組成的數組
函數
filter 返回 該函數 會返回true的項 組成的數組
spa
forEach 無返回值
ES5的方法code
every 數組全部項都返回true 則返回true,相似&& 一旦有一個不符合條件,則中止迭代
blog
some 函數對數組裏面有一項返回true 則返回true,相似|| 不停的迭代找符合條件的值,一旦找到,則中止迭代
索引
代碼演示:回調函數
var arr = [1,2,3,4,5];
console.log(arr.map((item,index,arr)=>{ console.log('map: ', item, index ,arr); return item>2 })); 1. // 返回[false,false,true,true,true] console.log(arr.filter(function(item,index,arr){ console.log('filter: ', item,index,arr); return item>2; })); 2. // 返回 [3,4,5] console.log(arr.forEach(function(item,index,arr){ console.log('foreach: ', item,index,arr); return item>2; })); 3. // forEach無返回值 console.log(arr.every((item,index,arr) => { console.log('every: ', item, index, arr); return item>2; })); 4. // 返回false, 打印一遍every: console.log(arr.some((item, index, arr) => { console.log('some: ', item, index, arr); return item>2; })); 5. // 返回true,打印3遍some:
> demo1: forEach
arr.forEach(function(value, index) {
//參數一是:數組元素
//參數二是:數組元素的索引
}) //至關於數組遍歷的 for循環 沒有返回值 /*-------------------------------------------------*/ // forEach // 1. E字母是大寫的 var arr = ['a', 'b', 'c']; // 語法: 數組名.forEach(回調函數) arr.forEach(function(value) { console.log(value); }); // 2. 數組元素的值是第一個參數, 數組的下標是第二個參數 arr.forEach(function(v, i) { console.log('第' + i + '個元素的值是' + v); })
> demo2: filter
var arr = [12, 66, 4, 88, 3, 7];
var newArr = arr.filter(function(value, index) { //參數一是:數組元素 //參數二是:數組元素的索引 return value >= 20; }); console.log(newArr);//[66,88] //返回值是一個新數組
> demo3: some
// some 查找數組中是否有知足條件的元素
var arr = [10, 30, 4];
var flag = arr.some(function(value,index) { //參數一是:數組元素 //參數二是:數組元素的索引 return value < 3; }); console.log(flag);//返回值是布爾值,只要查找到知足條件的一個元素就立馬終止循環