JavaScript 中的数组对象提供了丰富的内置方法,用于处理数组中的元素。以下是一些常用的数组方法:

常用数组方法

  • push()pop():用于添加和移除数组末尾的元素。
  • shift()unshift():用于添加和移除数组开头的元素。
  • splice():用于添加、移除或替换数组中的元素。
  • slice():用于提取数组的一部分,返回一个新数组。
  • concat():用于合并两个或多个数组。
  • join():用于将数组中的元素连接成一个字符串。

push() 和 pop()

push() 方法可以向数组的末尾添加一个或多个元素,并返回新的长度。

let fruits = ['Apple', 'Banana'];
fruits.push('Cherry');
console.log(fruits); // ['Apple', 'Banana', 'Cherry']

pop() 方法用于移除数组的最后一个元素,并返回该元素。

let fruits = ['Apple', 'Banana', 'Cherry'];
let lastFruit = fruits.pop();
console.log(lastFruit); // 'Cherry'
console.log(fruits); // ['Apple', 'Banana']

shift() 和 unshift()

shift() 方法用于移除数组的第一个元素,并返回该元素。

let fruits = ['Apple', 'Banana', 'Cherry'];
let firstFruit = fruits.shift();
console.log(firstFruit); // 'Apple'
console.log(fruits); // ['Banana', 'Cherry']

unshift() 方法用于向数组的开头添加一个或多个元素,并返回新的长度。

let fruits = ['Banana', 'Cherry'];
fruits.unshift('Apple');
console.log(fruits); // ['Apple', 'Banana', 'Cherry']

更多数组方法 可以在文档中找到。

JavaScript 图标