[Javascript] The Array forEach method

Most JavaScript developers are familiar with the for loop. One of the most common uses of the for loop is to iterate through the items in an array. In this lesson, we will learn how to replace the for loop with the Array's forEach method - and shorten your code in the process.

function getStockSymbols(stocks) {
  var symbols = [];
  
  stocks.forEach(function(stock) {
    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 },
]);

console.log(JSON.stringify(symbols));
原文地址:https://www.cnblogs.com/Answer1215/p/4356375.html