类(伪)数组定义:
1、具有length属性
2、按索引方式存储数据
3、没有数组的方法
对象转为类数组,属性要为索引(非负整数)属性,必须有length属性,最好加上push,splice
var obj = {
'0' : 'a',
"1" : "b",
"2" : "c",
"length" : 3,
push : Array.prototype.push,
splice: Array.prototype.splice
}
obj.push("d");
上面的类数组调用push方法时,方法内部机制为:
Array.prototype.push = function(target){
this[this.length] = target;
this.length ++;
}
由此看出,类数组push的索引位为当前的length位:
var obj = {
"2" : "a",
'3' : 'b',
"length" : 2,
name : '数组',
push : Array.prototype.push,
splice: Array.prototype.splice
}
obj.push("c");
obj.push("d");
类数组存储能力非常强大,具有数组与对象的特性。