數組的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}
結果相同