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


当前回答

有两种方法可以在JavaScript中附加数组:

1) push()方法将一个或多个元素添加到数组的末尾,并返回数组的新长度。

var a = [1, 2, 3];
a.push(4, 5);
console.log(a);

输出:

[1, 2, 3, 4, 5]

2) unshift()方法将一个或多个元素添加到数组的开头,并返回数组的新长度:

var a = [1, 2, 3];
a.unshift(4, 5);
console.log(a); 

输出:

[4, 5, 1, 2, 3]

3) concat()方法用于合并两个或多个数组。此方法不会更改现有数组,而是返回一个新数组。

var arr1 = ["a", "b", "c"];
var arr2 = ["d", "e", "f"];
var arr3 = arr1.concat(arr2);
console.log(arr3);

输出:

[ "a", "b", "c", "d", "e", "f" ]

4) 可以使用数组的.length属性将元素添加到数组的末尾:

var ar = ['one', 'two', 'three'];
ar[ar.length] = 'four';
console.log( ar ); 

输出:

 ["one", "two", "three", "four"]

5) splice()方法通过删除现有元素和/或添加新元素来更改数组的内容:

var myFish = ["angel", "clown", "mandarin", "surgeon"];
myFish.splice(4, 0, "nemo");
//array.splice(start, deleteCount, item1, item2, ...)
console.log(myFish);

输出:

["angel", "clown", "mandarin", "surgeon","nemo"]

6) 您还可以通过指定新索引并赋值来向数组中添加新元素:

var ar = ['one', 'two', 'three'];
ar[3] = 'four'; // add new element to ar
console.log(ar);

输出:

["one", "two","three","four"]

其他回答

如果arr是数组,而val是要添加的值,请使用:

arr.push(val);

E.g.

var arr=[‘a’,‘b’,‘c’];arr.push('d');控制台日志(arr);

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

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

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

b = b.concat(a);

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

如果您使用的是ES6,则可以使用扩展运算符来执行此操作。

var arr = [
    "apple",
    "banana",
    "cherry"
];

var arr2 = [
    "dragonfruit",
    "elderberry",
    "fig"
];

arr.push(...arr2);

附加单个元素

// 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

现在,您可以利用ES6语法

let array = [1, 2];
console.log([...array, 3]);

保持原始数组不变。