map()
透過函式產生一個新陣列
不會改變原陣列
回傳等於原陣列
如不回傳是undefined
語法
const newArr = arr.map(function (value, index, array){
return ...
});
回調函式(callback)與三個參數:value,index,arr
const shoppingCart = [
{itemName: "Book",price : 220 },
{itemName: "Bag",price : 350 }
];
// 使用箭頭函示的縮寫
const itemNames = shoppingCart.map(x =>
x.itemName
);
console.log(itemNames )
// 只把 itemNames 提取出來
itemNames; // ["Book", "Bag"]
// 把 price 打七九折後提取出來
const discounts = shoppingCart.map(x => x.price * 0.79);
discounts;
console.log('折扣:discounts',discounts)
// [173.8, 276.5]
//小於 50標示無折扣
const prices = [42, 57, 89, 23, 78, 12]
const newPrices = prices.map( function(elem) {
if(elem < 50) return "無折扣";
return elem
});
newPrices;
console.log(newPrices)
//["無折扣",57,89,"無折扣",78,"無折扣"]
價格大於999元,均8折
map() & Math.max 取出最大值