合并数组中的第一个数组项

时间:2017-08-27 06:00:04

标签: javascript arrays

我有一个数组数组。我想合并数组中每个数组的第一项。我怎么能这样做?

这是我的数组:

var array = [["plums", "peaches", "pineapples"], ["carrots", "corn", "green beans"], ["chocolate", "ice cream"]];

我希望输出为:

var newArray = ["plums", "carrots", "chocolate"];

这就是我的尝试:

<!doctype html>
<html>
<body>
<script>
  var array = [["plums", "peaches", "pineapples"], ["carrots", "corn", "green beans"], ["chocolate", "ice cream"]];

  var arrLength = array.length;
  var newArray = [];

  for (var i = 0; i < arrLength; i++) {
newArray = [].concat.apply([], array[i][0]);
  };
  console.log("new merged array:", newArray);

</script>
</body>
</html>

但是,在控制台中,我收到此错误:

  

在非对象上调用CreateListFromArrayLike。

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:2)

您可以使用Array.prototype.map()。阅读更多here

var array = [["plums", "peaches", "pineapples"], ["carrots", "corn", "green beans"], ["chocolate", "ice cream"]];
var newArray = array.map(x => x[0])

但是,如果你想使用for循环来迭代元素,你可以这样做,

var newArray = []
for (let i = 0; i < array.length; i++) {
    // Since you want the first element,
    newArray.push(array[i][0])
}