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

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用法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值