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


当前回答

附加单个元素

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

其他回答

如果要将单个值附加到数组中,只需使用push方法。它将在数组末尾添加一个新元素。

但是,如果您打算添加多个元素,请将这些元素存储在一个新数组中,并将第二个数组与第一个数组连接起来。。。无论你想怎样。

arr=['a','b','c'];
arr.push('d');
//now print the array in console.log and it will contain 'a','b','c','d' as elements.
console.log(array);

让数组长度属性执行以下操作:

myarray[myarray.length] = 'new element value added to the end of the array';

myarray.length返回数组中的字符串数。JavaScript是从零开始的,因此数组的下一个元素键将是数组的当前长度。

例子:

var myarray = [0, 1, 2, 3],
    myarrayLength = myarray.length; // myarrayLength is set to 4

有两种方法可以在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"]

在数组上追加项

let fruits = ["orange", "banana", "apple", "lemon"]; /* Array declaration */

fruits.push("avacado"); /* Adding an element to the array */

/* Displaying elements of the array */

for(var i=0; i < fruits.length; i++){
  console.log(fruits[i]);
}

使用新的ES6排列运算符,使用push连接两个阵列变得更加容易:

var arr=[1,2,3,4,5];var arr2=[6,7,8,9,10];arr.push(…arr2);控制台日志(arr);

这会将arr2的内容添加到arr的末尾。

Babel REPL示例