类数组
1.类数组的特性
- 可以利用属性名模拟数组的特性
- 可以动态的增长length属性
- 如果强行让类数组调用push方法,则会根据length属性值的位置进行属性的扩充
例如,实参列表arguments就是一个类数组。
2.类数组的组成
- 属性要为索引(数字)属性
- 必须要有length属性
- 最好加上push方法
例如
var obj = {
"0" : "a",
"1" : "b",
"2" : "c",
"length" : 3,
"push" : Array.prototype.push
};
Array的push方法的原理:
Array.prototype.push = function (target) {
obj[obj.length] = target;
obj.length ++;
}
利用push方法可以为类数组添加属性:
var obj = {
"0" : "a",
"1" : "b",
"2" : "c",
"length" : 3,
"push" : Array.prototype.push
};
obj.push("d");
obj.push("e");
//push后的obj为
// var obj = {
// "0" : "a",
// "1" : "b",
// "2" : "c",
// "3" : "d",
// "4" : "e",
// "length" : 5,
// "push" : Array.prototype.push
// };
var obj = {
"2" : "a",
"3" : "b",
"length" : 2,
"push" : Array.prototype.push,
};
obj.push("c");
obj.push("d");
//push后的obj为
// var obj = {
// "2" : "c",
// "3" : "d",
// "length" : 4,
// "push" : Array.prototype.push
// };
在类数组中添加splice属性后,浏览器控制台中,类数组显示出来就会由{}变为[]