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循环实现:
for (i = 0; i < stocks.length; i++) {
stock = stocks[i];
symbols.push(stock.symbol);
}
stock = stocks[i];
symbols.push(stock.symbol);
}
return symbols;
}
var symbols = getStockSymbols([
{ symbol: "XFX",{ symbol: "TNZ",{ symbol: "JXJ",]);
输出: "[/"XFX/","TNZ/","JXJ/"]"
你也可以采用Array的forEach方法来简化代码,它们的输出是完全一样的。
stocks.forEach(function(stock) {
symbols.push(stock.symbol);
});
原文链接:https://www.f2er.com/js/49878.htmlsymbols.push(stock.symbol);
});
return symbols;
}