如何在JavaScript中将对象(如字符串或数字)附加到数组中?
当前回答
让数组长度属性执行以下操作:
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
其他回答
附加单个元素
// 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
只想添加一个片段,用于非破坏性地添加元素。
var newArr = oldArr.concat([newEl]);
当然,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);
您可以使用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' ]