如何在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和apply函数附加两个数组。
var数组1=[11,32,75];var数组2=[99,67,34];数组.原型.推送.应用(array1,array2);console.log(array1);
它将把array2追加到array1。现在数组1包含[11,32,75,99,67,34]。这段代码比编写循环来复制数组中的每个项要简单得多。
使用新的ES6排列运算符,使用push连接两个阵列变得更加容易:
var arr=[1,2,3,4,5];var arr2=[6,7,8,9,10];arr.push(…arr2);控制台日志(arr);
这会将arr2的内容添加到arr的末尾。
Babel REPL示例
我们在JavaScript中没有Array的append函数,但我们有push和unshift。假设您有以下阵列:
var arr = [1, 2, 3, 4, 5];
我们喜欢向这个数组附加一个值。我们可以执行arr.push(6),它将在数组末尾添加6:
arr.push(6); // Returns [1, 2, 3, 4, 5, 6];
我们还可以使用unshift,看看我们如何应用它:
arr.unshift(0); // Returns [0, 1, 2, 3, 4, 5];
它们是向数组添加或追加新值的主要函数。
如果要将单个值附加到数组中,只需使用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);
现在,您可以利用ES6语法
let array = [1, 2];
console.log([...array, 3]);
保持原始数组不变。