1.定義:有類似數組的屬性、方法的特殊對象,最典型的是 arguments
2. arguments 特點:
function a(a,b){console.log(arguments)}
a(1,2);
可以看到控制台輸出的是一個特殊的數組(數組也是對象。。),包含兩個可編輯的屬性 0 1 ,不可編輯的 callee( 指向函數本身 )、length...
並沒有 Array.prototype 那一大堆屬性和方法喔
3.自定義類數組:以 push 方法為例 ( push 底層實現是 在原有數組末尾增加元素,並改變原數組的長度,即 length 屬性的值 )
var obj={
0:'a',
1:'b',
length:2,
push:Array.prototype.push
}
obj // {0: "a", 1: "b", length: 2, push: ƒ}
obj.push(3)
obj // {0: "a", 1: "b", 2: 3, length: 3, push: ƒ}
如果再增加一個數組原型對象的 splice 方法,就和 arguments 非常相似了
var obj={
0:'a',
1:'b',
length:2,
push:Array.prototype.push,
splice:Array.prototype.splice
}
obj // ["a", "b", push: ƒ, splice: ƒ]
4. push 使用后變化
var obj={
2:'a',
3:'b',
length:2,
push:Array.prototype.push
}
obj.push(1)
obj // {2: 1, 3: "b", length: 3, push: ƒ}
原理就是 push 后 length +1,然后數組下標從 0 開始計算, 最后覆蓋原位置屬性對應的值。
5. 擴展 push 方法
5.1 push 一個數組 : apply 方法的妙用
var arr1=[1,2],arr2=[2,3];
Array.prototype.push.apply(arr1,arr2)
arr1 // [1,2,2,3]
5.2 push 一系列數據(區分 基本參數和數組形式參數): 遞歸妙用
Array.prototype.mypush=function(){
var that=this;
function unitpush(arr,obj){
for(var i=0,j=arr.length;i<j;i++){
if(Object.prototype.toString.call(arr[i])==='[object Array]'){
unitpush(arr[i],that);
}else{
obj[obj.length]=arr[i];
}
}
}
unitpush(arguments,that);
return that;
}
[1].mypush(2,[3,4]) // [1, 2, 3, 4]
[1].mypush(2,[3,4],[5,[6,[7,8]]]) // [1, 2, 3, 4, 5, 6, 7, 8]