Array.prototype.shift()、Array.prototype.unshift()方法
作者:互联网
1. Array.prototype.shift()方法
(1)定义:用于删除数组的第一个元素,并返回该元素。注意,该方法会改变原数组
1 var a = ['a', 'b', 'c']; 2 3 a.shift() // 'a' 4 a // ['b', 'c']
上面代码中,使用shift()
方法以后,原数组就变了
(2)shift()
方法可以遍历并清空一个数组
1 var list = [1, 2, 3, 4]; 2 var item; 3 4 while (item = list.shift()) { 5 console.log(item); 6 } 7 8 list
上面代码通过list.shift()
方法每次取出一个元素,从而遍历数组。它的前提是数组元素不能是0
或任何布尔值等于false
的元素,因此这样的遍历不是很可靠
2. push()
和shift()
结合使用,就构成了“先进先出”的队列结构(queue)
3. Array.prototype.unshift()方法
(1)定义:用于在数组的第一个位置添加元素,并返回添加新元素后的数组长度。注意,该方法会改变原数组
1 var a = ['a', 'b', 'c']; 2 a.unshift('x'); // 4 3 a // ['x', 'a', 'b', 'c']
(2)unshift()
方法可以接受多个参数,这些参数都会添加到目标数组头部
1 var arr = [ 'c', 'd' ]; 2 arr.unshift('a', 'b') // 4 3 arr // [ 'a', 'b', 'c', 'd' ]
标签:shift,unshift,list,数组,var,Array,prototype 来源: https://www.cnblogs.com/icyyyy/p/14750578.html