伪数组及其转换为真数组原理
什么是伪数组
定义:
拥有length属性和数值下标属性。
不具有数组所具有的方法。
常见的伪数组
参数数组:arguments
DOM对象列表HTMLCollection():比如通过document.getElementsByTagName得到的列表
jquery对象:比如$("div")
举例
通过document.getElementsByTagName得到的DOM对象列表是一个伪数组。
- test1
- test2
- test3
- test4
const lis = document.getElementsByTagName('li');
console.log(lis); // HTMLCollection(4) [li, li, li, li]
伪数组是一个Object,而真实的数组是一个Array
console.log(lis instanceof Array); // false
console.log(lis instanceof Object); // true
拥有length属性和数值下标属性
console.log(lis[1]); //
test2console.log(lis.length); // 4
伪数组没有真实数组的方法
console.log(lis.forEach) //undefined
lis.forEach((ele) => console.log(ele))
真实数组的forEach()方法:
const ll = [1,2,3];
ll.forEach((ele) => console.log(ele))
Array.prototype.slice.call(lis)将伪数组转换为真数组
// Array.prototype.slice.call(lis):将伪数组转换为真数组
const lis2 = Array.prototype.slice.call(lis); // 相当于 lis.slice()
console.log(lis2 instanceof Array); //true
console.log(lis2 instanceof Object); //true
console.log(lis2[1]); //
test2console.log(lis2.forEach); // ƒ forEach() { [native code] }
原理
数组的slice()截取数组中指定部分的元素, 生成一个新的数组 [1, 3, 5, 7, 9],slice(0, 3)
// slice2()
Array.prototype.slice2 = function (start, end) {
start = start || 0
end = start || this.length
const arr = []
for (var i = start; i < end; i++) {
arr.push(this[i])
}
return arr
}