1. splice()操作方法
splice意为拼接,捻接(有一个api形近词意为slice 切片的单词,可用于软靠背)
在JavaScript的Array对象中提供了一个splice()方法用于对数组进行特定的操作。splice()恐怕要算最强大的数组方法了,他的用法有很多种,在此只介绍删除数组元素的方法。在删除数组元素的时候,它可以删除任意数量的项,只需要指定2个参数:要删除的第一项的位置和要删除的项数。
var colors = ["red", "blue", "grey"];
var color = colors.splice(0, 1);
console.log(color); // "red"
console.log(colors); // ["blue", "grey"]
2. pop()栈方法
pop意为弹出,弹出并返回数组中的最后一项,某种程度上也可以当做删除用。
JavaScript中的Array对象提供了一个pop()栈方法用于
栈数据结构的访问规则是FILO(First In Last Out,先进后出),栈操作在栈顶添加项,从栈顶移除项,使用pop()方法,它能移除数组中的最后一项并返回该项,并且数组的长度减1。
var colors = ["red", "blue", "grey"];
var color = colors.pop();
console.log(color); // "grey"
console.log(colors); // ["red", "blue"]
console.log(colors.length); // 2
3. shift()队列方法
shift,意为改变,转换,移位。是键盘上的shift键。
JavaScript中的Array对象提供了一个shift()队列方法用于弹出并返回数组中的第一项,某种程度上也可以当做删除用。
队列数据结构的访问规则是FIFO(First In First Out,先进先出),队列在列表的末端添加项,从列表的前端移除项,使用shift()方法,它能够移除数组中的第一个项并返回该项,并且数组的长度减1。
var colors = ["red", "blue", "grey"];
var color = colors.shift();
console.log(color); // "red"
console.log(colors);// ["blue", "grey"]
console.log(colors.length); // 2
4. delete 和 length
delete操作符可以删除数组的任意可改变元素,但是length不会改变,下标也不会改变。
var colors = ["red", "blue", "grey"];
delete colors[0];
console.log(colors); // [undefined, "blue", "grey"]
console.log(colors.length); // 3
数组的length长度是可写的,可以通过length长度来删除数组末尾元素
var colors = ["red", "blue", "grey"];
colors.length = 2;
console.log(colors); // ["red", "blue"]
console.log(colors.length); // 2