如何通过javascript将数据数组推送到另一个数组而不循环

How to push the array of data to another array through javascript without loop

本文关键字:数组 另一个 循环 何通过 javascript 数据      更新时间:2023-09-26

我有一个Json数组,如数据{"alphaNumeric":[]}。这里我只是想将对象的另一个数组[mentioned below]推入这个Data,并带有out循环的概念。

data{"numeric":[{"id":"1","alpha":"a"},{"id":"2","alpha":"b"}]}.

我使用了下面的代码:data.alphaNumeric.push(data.numeric);

但是输出是:

data{"alphaNumeric":[[{"id":"1","alpha":"a"},{"id":"2","alpha":"b"}]]}.

期望:

data{"alphaNumeric":[{"id":"1","alpha":"a"},{"id":"2","alpha":"b"}]}.

一种解决方案可能是使用concat方法。这不是很好,因为它创建了一个全新的数组。

b.alphaNumeric = b.alphaNumeric.concat(a.numeric);

但是使用push有一个更好的解决方案。它接受不止一个元素,但不幸的是不是作为数组。这可以通过apply方法来实现:

b.alphaNumeric.push.apply(b.alphaNumeric, a.numeric);

你也可以写你自己的方法(我叫它add),它会为你做这个动作:

Array.prototype.add = function (array) {
  this.push.apply(this, array);
  return this;
};
b.alphaNumeric.add(a.numeric);

使用 concat()

data.alphaNumeric.concat(data.numeric);

.push().pop()用于添加和删除数组中的单个元素。.concat()的返回值就是您要查找的:

var newArr = oldArr.concat(extraArr);