下面的代碼輸出結果是:
let obj = {
2:3,
3:4,
length: 2,
push: Array.prototype.push
}
obj.push(1);
obj.push(2);
console.log(obj)
分析:
obj是一個對象裏面有四個屬性,包括push 方法,正常情況下對象是沒有push() 方法的,那麼push()方法做什麼?或者怎麼實現一個 push() 方法?
如下:
// 實現簡易版 push() 方法, 原理:在數組的末尾添加傳入的值,改變數組長度並返回數組;
Array.prototype.push = function(num){
// this 指向當前Array
// 默認會使 length 屬性加1, 如果沒有 length 屬性那麼 push() 方法會默認 length爲0;
this.length = this.length || 0;
return this[this.length] = num;
}
let arr = [1,2];
arr.push(3); // => arr = [1,2,3];
通過上面的 push() 解析,可以得知:
obj.push(1) // => 執行this[this.length] length爲2 this[2] = 1;
obj.push(2) // => 執行this[this.length] length爲3 this[3] = 2;
console.log(obj) // => obj = {2:1, 3:2, length: 4, push: Array.prototype.push}