Array.prototype.push()、Array.prototype.pop()方法

1. Array.prototype.push()方法

(1)定义:用于在数组的末端添加一个或多个元素,并返回添加新元素后的数组长度。注意,该方法会改变原数组

(2)代码使用push方法,往数组中添加了四个成员

1 var arr = [];
2 console.log(arr.push(1)); //1
3 console.log(arr.push('a')); //2 
4 console.log(arr.push(true,{}));//4
5 console.log(arr); // [1, 'a', true, {}]

2. Array.prototype.pop()方法

(1)定义:删除数组的最后一个元素,并返回该元素。注意,该方法会改变原数组

1 var arr = ['a', 'b', 'c'];
2 arr.pop();  // 'c'
3 arr; // ['a', 'b']

(2)对空数组使用pop方法,不会报错,而是返回undefined

1 [].pop() // undefined

3. pushpop结合使用,就构成了“后进先出”的栈结构(stack)

1 var arr = [];
2 arr.push(1, 2); // 2
3 arr.push(3);  // 3
4 arr.pop(); //3
5 arr; //[1,2]

上面代码中,3是最后进入数组的,但是最早离开数组

posted @ 2021-05-08 12:19  icyyyy  阅读(122)  评论(0)    收藏  举报