JavaScript的數組迭代器函數map和filter,可以遍歷數組時產生新的數組,和python的map函數很類似
1> filter是滿足條件的留下,是對原數組的過濾;
2> map則是對原數組的加工,映射成一一映射的新數組
1 let arr = [1, 2, 3, 4]; 2 let newArr = arr.map(function(item) { // 使用map方法 3 return item * 2; 4 }); 5 console.log(newArr); // [2, 4, 6, 8] 6 7 8 let arr = [1, 2, 3, 4]; 9 let newArr = arr.filter(function(item) { // 使用filter方法 10 if (item % 2 !== 0) { 11 return item; 12 } 13 }); 14 console.log(newArr); // [1, 3];
