在学习的过程中,敲写自己的学习笔记
本文粗略的记录了类数组的一些要点。只讲对象型的类数组
JS :初探类数组(对象型的)
类数组:是对象,但能当对象用,也能当数组用
类数组要求:属性要为索引(数字)属性,必须要有length属性,最好加上push方法
例子:
var obj = {
'0' : 'a',
'1' : 'b',
'2' : 'c',
length : 3,
push : Array.prototype.push,
splice : Array.prototype.splice //加了这个,一个对象就很像一个数组了
}
在后台:
obj.push(‘d’)
则
obj = {
'0' : 'a',
'1' : 'b',
'2' : 'c',
'3' : 'd',
length : 4,
push : Array.prototype.push,
splice : Array.prototype.splice //加了这个,一个对象就很像一个数组了
}
push方法的大概原理:
Array.prototype.push = function(target){
this.[this.length] = target;
this.length ++;
}
那么换成 类数组 obj ,就是:
Array.prototype.push = function(target){
obj.[obj.length] = target;
obj.length ++;
}
下面通过一道阿里真题来灵活使用
var obj = {
'2' : 'a',
'3' : 'b',
length : 2,
push : Array.prototype.push
}
obj.push('c');
obj.push('d');
//求此时obj的值
这道题按照push的方法原理
Array.prototype.push = function(target){
this.[this.length] = target;
this.length ++;
}
将2放进去对应
'2': 'c',此时length为3
将3放进去对应
'3': 'd',此时length为4
所以
obj = {
'2' : 'c',
'3' : 'd',
length : 4,
push : Array.prototype.push
}

本文深入探讨JavaScript中类数组的概念,解析其特点与使用方法,包括属性要求、push方法原理及应用实例,帮助读者掌握类数组的灵活运用。
992

被折叠的 条评论
为什么被折叠?



