JavaScript 的数组方法 push()
, pop()
, shift()
, 和 unshift()
是用来修改数组的内容的。
push()
方法将一个或多个元素添加到数组的末尾,并返回新的长度。pop()
方法删除并返回数组的最后一个元素。shift()
方法删除并返回数组的第一个元素。unshift()
方法将一个或多个元素添加到数组的开头,并返回新的长度。
以下是一些使用这些方法的例子:
// 创建一个数组
let arr = [1, 2, 3, 4, 5];
// 使用 push 方法添加元素到数组末尾
arr.push(6); // arr is now [1, 2, 3, 4, 5, 6]
console.log(arr); // 输出: [1, 2, 3, 4, 5, 6]
// 使用 pop 方法删除并返回数组的最后一个元素
let lastElement = arr.pop(); // lastElement is now 6, arr is now [1, 2, 3, 4, 5]
console.log(lastElement); // 输出: 6
console.log(arr); // 输出: [1, 2, 3, 4, 5]
// 使用 shift 方法删除并返回数组的第一个元素
let firstElement = arr.shift(); // firstElement is now 1, arr is now [2, 3, 4, 5]
console.log(firstElement); // 输出: 1
console.log(arr); // 输出: [2, 3, 4, 5]
// 使用 unshift 方法添加元素到数组开头
arr.unshift(0); // arr is now [0, 2, 3, 4, 5]
console.log(arr); // 输出: [0, 2, 3, 4, 5]