js数组操作的shift unshift pop push用法

发布时间 2023-08-22 11:24:59作者: weimiu

Array.shift()

shift() 方法用在数组上, 移除数组的第一个元素并返回移除的元素. 该方法会改变原数组的长度.

const array1 = [1, 2, 3];
const firstElement = array1.shift();
console.log(array1); // Expected output: Array [2, 3]
console.log(firstElement); // Expected output: 1
如果数组为空,返回undefined
[].shift() // undefined


Array.unshift()

unshift()方法用在数组上,在数组的头部添加元素,可多个,并且返回新数组的长度。

const array1 = [1, 2, 3];
console.log(array1.unshift(4, 5)); // Expected output: 5
console.log(array1); // Expected output: Array [4, 5, 1, 2, 3]


Array.push()

The push() method of Array instances adds the specified elements to the end of an array and returns the new length of the array.

跟unshift用法一样,返回的也是新数组的长度。只不过push从数组尾部插入元素

const animals = ['pigs', 'goats', 'sheep'];
const count = animals.push('cows');
console.log(count); // Expected output: 4
console.log(animals); // Expected output: Array ["pigs", "goats", "sheep", "cows"]
animals.push('chickens', 'cats', 'dogs');
console.log(animals); // Expected output: Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]


Array.pop()

The pop() method of Array instances removes the last element from an array and returns that element. This method changes the length of the array.

跟shift用法差不多,只不过shift从头部移除,pop从数组尾部移出元素,返回的都是移除的元素。

const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];
console.log(plants.pop()); // Expected output: "tomato"
console.log(plants); // Expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]
plants.pop();
console.log(plants); // Expected output: Array ["broccoli", "cauliflower", "cabbage"]




参考:js数组操作的shift unshift pop push用法