一、什么是JS的伪/类数组?
- 有length属性
- 按索引排序
- 不能使用数组方法
- 可以使用for循环
如何转为标准数组
- Array.prototype.slice.call(arguments)
- Array.prototype.splice.call(arguments, 0)
- Array.from(arguments)
- Array.prototype.concat.apply([], arguments)
三、示例
window.onload = function() {
function nodeList() {
// 方法一: Array.prototype.slice.call(arguments)
// 方法二: Array.prototype.splice.call(arguments)
// 方法三: Array.prototype.concat.apply([],arguments)
// 方法四: Array.from(arguments)
return Array.prototype.slice.call(arguments);
}
let arr = nodeList(1, 2, 3, 4, 5, 6, 7);
arr.push(20);
console.log('arr:', arr);
}