Tuesday, April 24, 2018

javascript - How to append something to an array?




How do I append an object (such as a string or number) to an array in JavaScript?



Answer



Use the Array.prototype.push method to append values to an array:





// initialize array
var arr = [
"Hi",
"Hello",
"Bonjour"

];

// append new value to the array
arr.push("Hola");

console.log(arr);









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]);
}









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);





Update



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 Array.prototype.unshift for this purpose.






var arr = [1, 2, 3];
arr.unshift(0);
console.log(arr);





It also supports appending multiple values at once just like push.


No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...