JavaScript Array Methods Guide
In JavaScript, an array is a special type of object used to store multiple values. Arrays offer a range of methods for manipulating and processing data within them. Below is a detailed explanation of some commonly used array methods.
- push(): Add one or more elements to the end of the array, and return the new length of the modified array.
var fruits = ['apple', 'banana'];
fruits.push('orange'); // 返回3
console.log(fruits); // 输出['apple', 'banana', 'orange']
- pop() removes the last element of an array and returns the value of the removed element.
var fruits = ['apple', 'banana', 'orange'];
var lastFruit = fruits.pop(); // 返回'orange'
console.log(fruits); // 输出['apple', 'banana']
- The shift() method removes the first element from an array and returns the value of the removed element.
var fruits = ['apple', 'banana', 'orange'];
var firstFruit = fruits.shift(); // 返回'apple'
console.log(fruits); // 输出['banana', 'orange']
- unshift(): add one or more elements to the beginning of an array and return the new length of the modified array.
var fruits = ['apple', 'banana'];
fruits.unshift('orange'); // 返回3
console.log(fruits); // 输出['orange', 'apple', 'banana']
- concat(): Merge two or more arrays into a new array and return it.
var fruits1 = ['apple', 'banana'];
var fruits2 = ['orange', 'peach'];
var allFruits = fruits1.concat(fruits2); // 返回['apple', 'banana', 'orange', 'peach']
console.log(allFruits);
- slice(): Extracts a specified section from an array and returns a new array with the extracted section.
var fruits = ['apple', 'banana', 'orange', 'peach'];
var citrusFruits = fruits.slice(1, 3); // 返回['banana', 'orange']
console.log(citrusFruits);
- splice(): Removes elements from an array and can insert new elements at the removed positions.
var fruits = ['apple', 'banana', 'orange'];
fruits.splice(1, 1, 'kiwi', 'mango'); // 删除数组第2个元素,并在该位置插入'kiwi'和'mango'
console.log(fruits); // 输出['apple', 'kiwi', 'mango', 'orange']
- reverse() function: reverse the order of elements in the array and return the modified array.
var fruits = ['apple', 'banana', 'orange'];
fruits.reverse();
console.log(fruits); // 输出['orange', 'banana', 'apple']
- sort(): sorts the array elements and returns the modified array.
var fruits = ['apple', 'banana', 'orange'];
fruits.sort();
console.log(fruits); // 输出['apple', 'banana', 'orange']
- join() method converts all the elements in an array into a single string and returns that string.
var fruits = ['apple', 'banana', 'orange'];
var fruitString = fruits.join(', ');
console.log(fruitString); // 输出'apple, banana, orange'
The above are some commonly used array methods that can help us manipulate and process array data more flexibly in JavaScript.