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; }