20.JavaScript学习笔记——类数组

类数组

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属性后,浏览器控制台中,类数组显示出来就会由{}变为[]

类数组splice

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值