类数组
1、都有length属性
2、类数组也可以for循环遍历,有的类数组还可以通过 for of 遍历
3、类数组不具备数组的原型方法,因此类数组不可调用相关数组方法(如,push,slicec,concat等等)
常见的类数组有
函数的参数arguments
通过getElementsByTagName,getElementsByClassName,getElementsByName等方法获取的dom列表(也叫 HTMLCollection)
通过querySelectorAll()方法获取的NodeList节点列表
push方法:
var obj = {
'2': 3,
'3': 4,
'length': 2,
'splice': Array.prototype.splice,
'push': Array.prototype.push
}
obj.push(1)
obj.push(2)
console.log(obj)
push 方法有意具有通用性,该方法和 call() 或 apply() 一起使用时,可应用在类似数组的对象上。它有几个特点,
- push 方法根据 length 属性来决定从哪里开始插入给定的值。
- 如果 length 不能被转成一个数值,则会赋值为0,包括 length 不存在时。当 length 不存在时,将会创建它。
- 当执行结束之后,length + 1
所以结合上面push方法的特点,可以得到
当执行obj.push(1)的时候,length为2,所以,obj[obj.lenght] = 1 ;即 obj[2] = 1;然后length+1
当执行obj.push(2)的时候,length为3,所以,obj[obj.lenght] = 2;即 obj[3] = 2;然后length+1
所以最后输出为:
{ '2': 1, '3': 2, length: 4, splice: [Function: splice], push: [Function: push]}
观后习题
var obj = {
'2': 3,
'3': 4,
'splice': Array.prototype.splice,
'push': Array.prototype.push
}
obj.push(1)
obj.push(2)
console.log(obj)
输出是多少?
答案看评论区