1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| 使用 map() 時他需要回傳一個值,他會透過函式內所回傳的值組合成一個陣列。 如果不回傳則是 undefined,回傳數量等於原始陣列的長度 -> 適合將原始的變數運算後重新組合一個新的陣列。 -------- var mapEmpty = people.map(function(item, index, array){ }); console.log(mapEmpty); // [undefined, undefined, undefined, undefined]
var mapAgeThan5 = people.map(function(item, index, array){ return item.age > 5; // 比較大於五歲的 }); console.log(mapAgeThan5); // [true, true, false, false]
var mapAgeThan5_2 = people.map(function(item, index, array){ // 錯誤示範 if (item.age > 5) { return item; // 回傳大於五歲的 } return false; // 別以為空的或是 false 就不會回傳 }); console.log(mapAgeThan5_2); // [{name: 'David'...}, {name: 'Mary'...}, false, false]
var mapEat = people.map(function(item, index, array){ if (item.like !== '蘿蔔泥') { return `${item.like} 好吃`; } else { return `${item.like} 不好吃`; } }); console.log(mapEat); // ["鍋燒意麵 好吃", "炒麵 好吃", "蘿蔔泥 不好吃", "蘿蔔泥 不好吃"]
|