Array.prototype.forEach()方法讓陣列的每一項都執行一次給定的函數。 — MDN
假設有這麼一個場景,你拿到了這麼一個陣列
[
{ symbol: "XFX", price: 240.22, volume: 23432 },
{ symbol: "TNZ", price: 332.19, volume: 234 },
{ symbol: "JXJ", price: 120.22, volume: 5323 },
]
你需要為其中的symbol建立一個新陣列, 也就是
[ "XFX", "TNZ", "JXJ"]
一般可以用for迴圈實現:
function getStockSymbols(stocks) { var symbols = [], stock, i; for (i = 0; i < stocks.length; i++) { stock = stocks[i]; symbols.push(stock.symbol); } return symbols; } var symbols = getStockSymbols([ { symbol: "XFX", price: 240.22, volume: 23432 }, { symbol: "TNZ", price: 332.19, volume: 234 }, { symbol: "JXJ", price: 120.22, volume: 5323 }, ]);
輸出: "[/"XFX/", "TNZ/", "JXJ/"]"
你也可以採用Array的forEach方法來簡化程式碼,它們的輸出是完全一樣的。
function getStockSymbols(stocks) { var symbols = []; stocks.forEach(function(stock) { symbols.push(stock.symbol); }); return symbols; }