美文网首页
数组的方法push、pop、unshift、shift、dele

数组的方法push、pop、unshift、shift、dele

作者: wjm91 | 来源:发表于2020-05-15 19:44 被阅读0次

push、pop、unshift、shift这四个操作都改变了原来的数组,未创建新数组。

push:向数组的尾部追加元素,直接在原来的数组尾部添加,不会创建新数组。

var a= new Array();

var b = a.push('a');

console.log(a);// ['a']

console.log(b);// 1

pop:删除并返回数组的最后一个元素,数组长度减 1,如果数组已经为空,则 pop() 不改变数组,并返回 undefined。

var a = ['a','b','c'];

var b = a.pop();

console.log(a);// ['a','b']

console.log(b);// c

unshift:向数组的开头添加一个或者过个元素,并返回新的长度,不会创建新数组,会直接修改原数组。

var a = ['a','b'];

var b = a.unshift('c');

console.log(a);// ['c','a','b']

console.log(b);// 3 返回的是修改后的数组长度,并未生成新数组

shift:删除第一个数组元素,并返回删除的元素的值,如果数组是空的,不进行任何操作,返回undefined,此方法不会创建新数组,修改原来的数组。

var a = ['a','b','c'];

var b = a.shift();

console.log(a);// ['b','c']

console.log(b);// a 返回的是删除的数组元素

push和pop实现了类似栈(LIFO last-in-first-out)的行为,后进先出。

splice:往数组中添加或者删除,返回被删除的元素,该方法会改变原来的数组。

arr.splice(index,howmany,item1,.....,itemX)

index:必填,整数,规定添加或删除的元素位置,使用负数可以从数组结尾处规定位置。

howmany:必填,要删除的元素数量,如果是0,就不删除,是添加元素。

item1,.....,itemX:可选,向数组添加的新元素。

// 向数组中添加元素

var a = ['a','b','c'];

var b = a.splice(1,0,'a1','a2');// 从下标1开始添加元素

console.log(a);// ["a", "a1", "a2", "b", "c"] 

console.log(b);// []

// 数组中删除元素

var a = ['a','b','c'];

var b = a.splice(1,1);// 从下标为1的地方,删除1个元素,删除下标为1的元素

console.log(a);//  ["a", "c"]

console.log(b);// ["b"]

// 数组中替换元素

var a = ['a','b','c'];

var b = a.splice(1,1,'d');// 替换下标为1的数组元素

console.log(a);// ["a", "d", "c"]

console.log(b);// ["b"] 

delete:数组长度不变

var a = ['a','b','c'];

delete a[1];

console.log(a);// ["a", empty, "c"]

相关文章

网友评论

      本文标题:数组的方法push、pop、unshift、shift、dele

      本文链接:https://www.haomeiwen.com/subject/usrhohtx.html