如何在JavaScript中将对象(如字符串或数字)附加到数组中?


当前回答

我认为值得一提的是,push可以用多个参数调用,这些参数将按顺序附加到数组中。例如:

var arr=['first'];arr.push('第二个','第三个');控制台日志(arr);

因此,您可以使用push.apply将一个数组附加到另一个数组,如下所示:

var arr=['first'];arr.push('第二个','第三个');arr.push.apply(arr,['forth','fifth']);控制台日志(arr);

带注释的ES5提供了更多关于推送和应用功能的信息。

2016年更新:使用spread,您不再需要应用,例如:

var arr=['first'];arr.push('第二个','第三个');arr.push(…['furth','fifth']);控制台日志(arr);

其他回答

如果要附加两个数组-

var a = ['a', 'b'];
var b = ['c', 'd'];

那么您可以使用:

var c = a.concat(b);

如果您想将记录g添加到数组(var a=[]),那么可以使用:

a.push('g');

您可以使用JavaScript Spread运算符语法:

// Initialize the array

var arr = [
    "Hi",
    "Hello",
    "Bangladesh"
];

// Append a new value to the array

arr = [...arr, "Feni"]; 

// Or you can add a variable value

var testValue = "Cool";

arr = [...arr, testValue ];

console.log(arr);

// Final output [ 'Hi', 'Hello', 'Bangladesh', 'Feni', 'Cool' ]

使用凹面:

a=[1,2,3];b=[3,4,5];a=混凝土(b);控制台日志(a);

附加单个元素

// Append to the end
arrName.push('newName1');

// Prepend to the start
arrName.unshift('newName1');

// Insert at index 1
arrName.splice(1, 0,'newName1');
// 1: index number, 0: number of element to remove, newName1: new element


// Replace index 3 (of exists), add new element otherwise.
arrName[3] = 'newName1';

附加多个元素

// Insert from index number 1
arrName.splice(1, 0,'newElemenet1', 'newElemenet2', 'newElemenet3');
// 1: index number from where insert starts,
// 0: number of element to remove,
//newElemenet1,2,3: new elements

附加一个数组

// Join two or more arrays
arrName.concat(newAry1, newAry2);
//newAry1,newAry2: Two different arrays which are to be combined (concatenated) to an existing array

当然,concat()也可以用于二维数组。无需循环。

var a = [
    [1, 2],
    [3, 4] ];

var b = [
    ["a", "b"],
    ["c", "d"] ];

b = b.concat(a);

alert(b[2][1]); // Result: 2