In JavaScript, there are several common methods to add new values to an existing array. Below, I'll outline three methods with specific examples to demonstrate how to use them.
Method 1: Using the push() Method
push() is one of the most commonly used methods, as it appends one or more elements to the end of an array and returns the new array length.
Example:
javascriptlet fruits = ['苹果', '香蕉']; fruits.push('橙子'); console.log(fruits); // Output: ['苹果', '香蕉', '橙子']
Method 2: Using the unshift() Method
If you want to add one or more elements to the beginning of an array, you can use the unshift() method.
Example:
javascriptlet numbers = [2, 3, 4]; numbers.unshift(1); console.log(numbers); // Output: [1, 2, 3, 4]
Method 3: Using the Spread Operator
The spread operator (...) allows array expressions or strings to be expanded during function calls or array construction. This feature can be used to add new elements to an array.
Example:
javascriptlet part1 = [1, 2, 3]; let part2 = [4, 5]; let combined = [...part1, ...part2]; console.log(combined); // Output: [1, 2, 3, 4, 5]
These methods can be chosen based on different requirements. The push() and unshift() methods directly modify the original array, whereas using the spread operator creates a new array without altering the original. The choice depends on the specific application scenario and requirements.