數組的push方法


數組的push方法相信大家都非常熟悉了,但是push方法的實現原理,又是怎么樣的呢,首先來看一道題:
let obj = {
    2: 'a',
    3: 'b',
    length: 2,
    push: Array.prototype.push
}

obj.push('c', 'd');
console.log(obj) 
 現在打印出來的obj是什么?
  答案:
 obj = {2:'c', 3: 'd', length: 4, push: Array.prototype.push}
 
為什么會這樣呢,來看一下push的實現原理就知道了
Array.prototype.myPush = function(...args) {
    for(let i = 0; i < args.length; i++) {
        this[this.length++] = args[i];
    }
    return this.length;
}

let obj1 = {
    2: 'a',
    3: 'b',
    length: 2,
    push: Array.prototype.myPush
}
obj1.push('c', 'd');
console.log(obj1) //{2:'c', 3: 'd', length: 4, push: Array.prototype.myPush}
結果相同
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM