如何在JavaScript中将对象(如字符串或数字)附加到数组中?
当前回答
使用凹面:
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
如果要将单个值附加到数组中,只需使用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排列运算符,使用push连接两个阵列变得更加容易:
var arr=[1,2,3,4,5];var arr2=[6,7,8,9,10];arr.push(…arr2);控制台日志(arr);
这会将arr2的内容添加到arr的末尾。
Babel REPL示例
您可以使用push方法。
Array.prototype.append = function(destArray){
destArray = destArray || [];
this.push.call(this, ...destArray);
return this;
}
var arr = [1,2,5,67];
var arr1 = [7,4,7,8];
console.log(arr.append(arr1)); // [7, 4, 7, 8, 1, 4, 5, 67, 7]
console.log(arr.append("Hola")) // [1, 2, 5, 67, 7, 4, 7, 8, "H", "o", "l", "a"]
您可以使用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' ]