问题描述
如何在JavaScript中将对象(如字符串或数字)附加到数组中?
How do I append an object (such as a string or number) to an array in JavaScript?
推荐答案
使用函数追加到数组:
Use the push()
function to append to an array:
// initialize array
var arr = [
"Hi",
"Hello",
"Bonjour"
];
// append new value to the array
arr.push("Hola");
console.log(arr);
将打印
["Hi", "Hello", "Bonjour", "Hola"]
您可以使用 push()
函数在一次调用中向一个数组附加多个值:
You can use the push()
function to append more than one value to an array in a single call:
// initialize array
var arr = [ "Hi", "Hello", "Bonjour", "Hola" ];
// append multiple values to the array
arr.push("Salut", "Hey");
// display all values
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
将打印
Hi
Hello
Bonjour
Hola
Salut
Hey
更新
如果如果要将一个数组的项添加到另一个数组,可以使用:
If you want to add the items of one array to another array, you can use firstArray.concat(secondArray)
:
var arr = [
"apple",
"banana",
"cherry"
];
arr = arr.concat([
"dragonfruit",
"elderberry",
"fig"
]);
console.log(arr);
将打印
["apple", "banana", "cherry", "dragonfruit", "elderberry", "fig"]
更新
如果您想将任何值附加到某个开头,请添加此答案数组意味着第一个索引然后你可以使用。
Just an addition to this answer if you want to append any value to the start of an array that means to the first index then you can use unshift() for this purpose.
var arr = [1, 2, 3]
arr.unshift(0)
console.log(arr)
将打印:
[0, 1, 2, 3]
它还支持多个值附加,就像push()方法一样。
It also supports multiple values appending just like push() method.
这篇关于如何将某些内容附加到数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!