我有一个JavaScript数组dataArray,我想把它推到一个新数组newArray。只是我不想让newArray[0]为dataArray。我想把所有的项都推入新数组:

var newArray = [];

newArray.pushValues(dataArray1);
newArray.pushValues(dataArray2);
// ...

或者更好:

var newArray = new Array (
   dataArray1.values(),
   dataArray2.values(),
   // ... where values() (or something equivalent) would push the individual values into the array, rather than the array itself
);

现在新数组包含了各个数据数组的所有值。是否有一些像pushValues这样的速记可用,这样我就不必遍历每个单独的数据数组,逐个添加项?


当前回答

我们有两个数组a和b,这里的代码是将数组a的值推入数组b。

let a = [2, 4, 6, 8, 9, 15]

function transform(a) {
    let b = ['4', '16', '64']
    a.forEach(function(e) {
        b.push(e.toString());
    });
    return b;
}

transform(a)

[ '4', '16', '64', '2', '4', '6', '8', '9', '15' ]

其他回答

我们有两个数组a和b,这里的代码是将数组a的值推入数组b。

let a = [2, 4, 6, 8, 9, 15]

function transform(a) {
    let b = ['4', '16', '64']
    a.forEach(function(e) {
        b.push(e.toString());
    });
    return b;
}

transform(a)

[ '4', '16', '64', '2', '4', '6', '8', '9', '15' ]

如果你想修改原始数组,你可以展开和推:

var source = [1, 2, 3];
var range = [5, 6, 7];
var length = source.push(...range);

console.log(source); // [ 1, 2, 3, 5, 6, 7 ]
console.log(length); // 6

如果你想确保源数组中只有相同类型的项(例如,不要混合数字和字符串),那么使用TypeScript。

/**
 * Adds the items of the specified range array to the end of the source array.
 * Use this function to make sure only items of the same type go in the source array.
 */
function addRange<T>(source: T[], range: T[]) {
    source.push(...range);
}

使用concat函数,如下所示:

var arrayA = [1, 2];
var arrayB = [3, 4];
var newArray = arrayA.concat(arrayB);

newArray的值将是[1,2,3,4](arrayA和arrayB保持不变;Concat为结果创建并返回一个新数组)。

var a=new Array('a','b','c');
var b=new Array('d','e','f');
var d=new Array('x','y','z');
var c=a.concat(b,d)

这能解决你的问题吗?

Тhis是一个工作代码,它工作得很好:

var els = document.getElementsByTagName('input'), i;
var invnum = new Array();
var k = els.length;
for(i = 0; i < k; i++){invnum.push(new Array(els[i].id,els[i].value))}