数组的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