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