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"]
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)