如何在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
其他回答
当然,concat()也可以用于二维数组。无需循环。
var a = [
[1, 2],
[3, 4] ];
var b = [
["a", "b"],
["c", "d"] ];
b = b.concat(a);
alert(b[2][1]); // Result: 2
如果要附加两个数组-
var a = ['a', 'b'];
var b = ['c', 'd'];
那么您可以使用:
var c = a.concat(b);
如果您想将记录g添加到数组(var a=[]),那么可以使用:
a.push('g');
如果arr是数组,而val是要添加的值,请使用:
arr.push(val);
E.g.
var arr=[‘a’,‘b’,‘c’];arr.push('d');控制台日志(arr);
让数组长度属性执行以下操作:
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
如果要将单个值附加到数组中,只需使用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);