JS数组操作之pop, push, unshift, splice, shift
在JavaScript编程中,数组是重要的数据结构之一。这里将讲解JS中常用的5种数组操作方法——pop, push, unshift, shift和 splice。
1. pop
pop()方法是用于移除并返回数组中的最后一个元素。它会改变原始的数组。
语法:
arr.pop()
示例1:
var fruits = ["apple", "banana", "orange"];
var poppedFruit = fruits.pop();
// 输出:poppedFruit: "orange", fruits: ["apple", "banana"]
console.log(`poppedFruit: ${poppedFruit}, fruits: ${fruits}`);
示例2:
var emptyArr = [];
var poppedItem = emptyArr.pop();
// 输出:poppedItem: undefined, emptyArr: []
console.log(`poppedItem: ${poppedItem}, emptyArr: ${emptyArr}`);
2. push
push()方法是用于向数组的末尾添加一个或多个元素。它也会改变原始的数组。
语法:
arr.push(element1, ..., elementN);
示例1:
var fruits = ["apple", "banana"];
var newLength = fruits.push("orange", "kiwi");
// 输出:newLength: 4, fruits: ["apple", "banana", "orange", "kiwi"]
console.log(`newLength: ${newLength}, fruits: ${fruits}`);
示例2:
var emptyArr = [];
var newLength = emptyArr.push(5);
// 输出:newLength: 1, emptyArr: [5]
console.log(`newLength: ${newLength}, emptyArr: ${emptyArr}`);
3. unshift
unshift()方法是用于向数组的开头添加一个或多个元素。它也会改变原始的数组。
语法:
arr.unshift(element1, ..., element);
示例1:
var fruits = ["orange", "kiwi"];
var newLength = fruits.unshift("apple", "banana");
// 输出:newLength: 4, fruits: ["apple", "banana", "orange", "kiwi"]
console.log(`newLength: ${newLength}, fruits: ${fruits}`);
示例2:
var emptyArr = [];
var newLength = emptyArr.unshift(5);
// 输出:newLength: 1, emptyArr: [5]
console.log(`newLength: ${newLength}, emptyArr: ${emptyArr}`);
4. splice
splice()方法可以用于添加或删除数组中的元素。它也会改变原始的数组。
语法:
arr.splice(start[, deleteCount[, element1[, ...[, elementN]]]])
- start:要修改的数组的开始索引
- deleteCount:要删除的元素个数。如果设置为0,则不删除元素
- element1, ..., elementN:要添加到数组中的元素
示例1:删除元素
var fruits = ["apple", "banana", "orange", "kiwi"];
var deletedFruits = fruits.splice(1, 2);
// 输出:deletedFruits: ["banana", "orange"], fruits: ["apple", "kiwi"]
console.log(`deletedFruits: ${deletedFruits}, fruits: ${fruits}`);
示例2:添加元素
var fruits = ["apple", "kiwi"];
var newFruits = fruits.splice(1, 0, "banana", "orange");
// 输出:newFruits: [], fruits: ["apple", "banana", "orange", "kiwi"]
console.log(`newFruits: ${newFruits}, fruits: ${fruits}`);
5. shift
shift()方法是用于移除并返回数组的第一个元素。它也会改变原始的数组。
语法:
arr.shift()
示例1:
var fruits = ["apple", "banana", "orange"];
var shiftedFruit = fruits.shift();
// 输出:shiftedFruit: "apple", fruits: ["banana", "orange"]
console.log(`shiftedFruit: ${shiftedFruit}, fruits: ${fruits}`);
示例2:
var emptyArr = [];
var shiftedItem = emptyArr.shift();
// 输出:shiftedItem: undefined, emptyArr: []
console.log(`shiftedItem: ${shiftedItem}, emptyArr: ${emptyArr}`);
以上就是JS数组操作之pop, push, unshift, splice, shift的完整攻略。希望能对您有所帮助!
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:js 数组操作之pop,push,unshift,splice,shift - Python技术站