Array栈方法
调用栈方法均会改变原数组
- push 入栈(返回值是数组的长度)
//在数组末尾添加元素
var arr = [1, 2, 3];
var res = arr.push(4, 5);
console.log(arr); // [1,2,3,4,5]
console.log(res); // arr.length 5
res = arr.push([6, 7]);
console.log(arr); // [1,2,3,4,5,[6,7]]
console.log(res); // arr.length 6
//合并两个数组
var arr1 = [1, 2, 3];
var arr2 = [4, 5];
//相当于是arr1.push(4, 5),这里充分利用apply的机制,将要添加的元素作为数组参数的项,调用push方法
var res = Array.prototype.push.apply(arr1, arr2);
console.log(arr1); // [1,2,3,4,5] arr1被改变
console.log(arr2); // [4,5]
console.log(res); // 5
//concat合并数组,不改变参与运算的数组,返回新数组
var arr1 = [1, 2, 3];
var arr2 = [4, 5];
var arr3 = arr1.concat(arr2);
console.log(arr1); // [1,2,3]
console.log(arr2); // [4,5]
console.log(arr3); // [1,2,3,4,5]
//像数组一样使用对象
var obj = {
length: 0,
addElem: function addElem (elem) {
// obj.length is automatically incremented
// every time an element is added.
[].push.call(this, elem);
}
};
// Let's add some empty objects just to illustrate.
obj.addElem({});
console.log(obj)
/**
* {
* 0:{},
* length:1,
* addElem: function...
* }
*/
- pop出栈(返回出栈的元素值)
var arr = [1];
var res = arr.pop();
console.log(arr); // []
console.log(res); // 1
res = arr.pop(); // 对空数组调用pop方法返回undefined
console.log(arr); // []
console.log(res); // undefined