How do I append an object (such as a string or number) to an array in JavaScript?
转载于:https://stackoverflow.com/questions/351409/how-to-append-something-to-an-array
How do I append an object (such as a string or number) to an array in JavaScript?
转载于:https://stackoverflow.com/questions/351409/how-to-append-something-to-an-array
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);
Will print
["Hi", "Hello", "Bonjour", "Hola"]
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]);
}
Will print
Hi
Hello
Bonjour
Hola
Salut
Hey
Update
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);
Will print
["apple", "banana", "cherry", "dragonfruit", "elderberry", "fig"]
</div>