Array.prototype.push()

push()方法將一個或多個元素添加到數組的末尾,並返回新數組的長度。數組

此方法會改變數組自身。app

添加元素到數組this

var sports = ["soccer", "baseball"];
var total = sports.push("football", "swimming");

console.log(sports); 
// ["soccer", "baseball", "football", "swimming"]

console.log(total);  
// 4

合併兩個數組spa

使用apply能夠將array參數變成arguments。prototype

var vegetables = ['parsnip', 'potato'];
var moreVegs = ['celery', 'beetroot'];

// 將第二個數組融合進第一個數組
// 至關於 vegetables.push('celery', 'beetroot');
Array.prototype.push.apply(vegetables, moreVegs);

console.log(vegetables); 
// ['parsnip', 'potato', 'celery', 'beetroot']

在對象上使用code

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({});
obj.addElem({});
console.log(obj.length);
// → 2

這樣操做的結果會發現obj變成了這樣:對象

{
    0: {},
    1: {},
    addElem: addElem(elem),
    length: 2
}

而且它的length也增加了。blog

本身實現簡單的push():ip

Array.prototype.push=function () {
  
for (var i=0;i<arguments.length;i++){
    
this[this.length]=arguments[i]
  }
  
return this.length;};
相關文章
相關標籤/搜索