小能豆

How to append something to an array?

javascript

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


阅读 157

收藏
2023-12-25

共1个答案

小能豆

You can use the push method to append elements to an array in JavaScript. Here’s an example:

// Create an array
let myArray = [1, 2, 3];

// Append a string to the array
myArray.push("four");

// Append a number to the array
myArray.push(5);

console.log(myArray); // Output: [1, 2, 3, "four", 5]

In this example, the push method is used to add elements to the end of the array. You can append multiple elements at once by passing them as arguments to the push method:

// Append multiple elements to the array
myArray.push("six", 7);

console.log(myArray); // Output: [1, 2, 3, "four", 5, "six", 7]

If you want to append elements to the beginning of the array, you can use the unshift method:

// Append elements to the beginning of the array
myArray.unshift("zero", -1);

console.log(myArray); // Output: ["zero", -1, 1, 2, 3, "four", 5, "six", 7]

Choose push or unshift based on whether you want to add elements to the end or the beginning of the array, respectively.

2023-12-25