類數組中:
如果沒有 splice 打印出來的是一個對象形式的結果
var obj = {
"2": 3,
"3": 4,
length: 2,
};
console.log(obj);
//{2: 3, 3: 4, length: 2}
如果加了 splice,打印出來,就是一個數組形式的結果
var obj = {
"2": 3,
"3": 4,
length: 2,
splice: Array.prototype.splice
};
console.log(obj);
//Object(2) [empty × 2, 2: 3, 3: 4, splice: ƒ]
關於類數組的一些注意點:
var obj = {
"2": 3,
"3": 4,
length: 2,
push: Array.prototype.push
};
obj.push(1);
obj.push(2);
console.log(obj);
//{2: 1, 3: 2, length: 4, push: ƒ}
注意這裏的返回結果,obj 並沒有4個屬性,相當於修改的原來的屬性,但長度變成了4。
原理就是 push 方法的源碼:
Array.prototype.push = function () {
for (var arg in arguments) {
if (arguments.hasOwnProperty(arg)) {
this[this.length] = arguments[arg];//push的時候,這裏使用的是 length 屬性
}
}
return this.length;
};