我们先理清类数组概念:
什么是类数组
长的像数组的对象,类数组又叫伪数组
类数组和数组的区别:
1.都有length属性
2.都可以for循环遍历,有的类数组还可以通过for of遍历
3.类数组不具备数组的原型方法,不可以调用相关数组方法(如,push、slice、concat…)
常见的类数组
1.函数的参数 arguments
2.通过getElementsByTagName,getElementsByClassName,getElementsByName等方法获取的dom列表(也叫HTML Collection)
3.通过querySelectorAll()方法获取的NodeList节点列表
方法:使用push方法,往类数组对象中推入一个值
1.通过实例对象来调
2.call方法
let { push } = [1, 2, 3]; let arr = { '0': 'terry', '1': 12, '2': 'xi', length: 3 } console.log(arr); //{ '0': 'terry', '1': 12, '2': 'xi', length: 3 } push.call(arr, 'tom'); //调用call方法 console.log(arr); //{ '0': 'terry', '1': 12, '2': 'xi', '3': 'tom', length: 4 }
3.操作原型