如何在JavaScript中将对象(如字符串或数字)附加到数组中?
当前回答
如果要附加两个数组-
var a = ['a', 'b'];
var b = ['c', 'd'];
那么您可以使用:
var c = a.concat(b);
如果您想将记录g添加到数组(var a=[]),那么可以使用:
a.push('g');
其他回答
push()将一个新元素添加到数组的末尾。
pop()从数组末尾删除元素。
要将对象(如字符串或数字)附加到数组,请使用:
array.push(toAppend);
有两种方法可以在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"]
如果要将单个值附加到数组中,只需使用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);
附加单个元素
// 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]);