什么是类数组对象?
参考答案
有 length 属性与数字索引,但没有数组方法的对象。
特征
typeof obj.length === 'number'且为非负整数;- 可通过
obj[0]访问元素; Array.isArray(obj) === false;- 可能有
callee(arguments)或item()(旧 NodeList)。
典型
arguments、NodeList、HTMLCollection、字符串、{0:'a', length:1}
转数组
Array.from(obj)、[...obj](需可迭代)、Array.prototype.slice.call(obj)
使用
可直接用索引与 length 遍历,或借用数组方法 Array.prototype.forEach.call(obj, fn)。