数组与伪数组

269 阅读1分钟

一. 什么是真数组(数组)?

    所谓真数组,其实可以直接称为:数组。
    当一个对象具有以下特点时,可以称为数组:
        1、可以按照索引的方式,存储多个数组;
        2、具有length属性,表示数组内数据的长度(个数);
        3、对象的原型属性__proto__,指向Array类,且可以使用Array的原型对象prototype身上的属性和方法,如pushpop

image.png

二、什么是伪数组?

    所谓伪数组,当一个对象具有以下特点:
        1、可以使用索引对数据进行操作;
        2、具有length(长度)属性;
        3、但是**不能使用数组的方法**,如pushpop等
    常见的伪数组:arguments、getElementsByTagName等一系列dom获取的NodeList对象
    

image.png

三、如何将伪数组转成真数组

方法1、遍历:创建一个空数组,循环遍历伪数组,将遍历出的数据逐一放在空数组中
    	const divs = document.querySelectorAll('div');
            let arr = [];
            console.log(divs instanceof Array);  // false
            for (let i = 0; i < divs.length;i++) {
                arr.push(divs[i]);
            } 
            console.log(arr instanceof Array);  // true

方法2Array.prototype.slice.call()
            const divs = document.querySelectorAll('div');
            console.log(divs instanceof Array); // false
            const arr = Array.prototype.slice.call(divs);  
            console.log(arr instanceof Array);  // true
     ??? slice方法为什么可以实现转换 就需要知道数组的slice方法内部实现原理 ???
      下面代码为简单模拟的slice方法:
          function slice(start,end){
                const startIndex = start || 0;
                const endIndex = end || this.length;
                let tempArr = [];
                for(let i = startIndex;i < endIndex;i++){
                  tempArr.push(this[i]);
                }
                return tempArr;
           }
      方法中的this就是能实现伪数组转换成真数组的关键,通过call()方法将this绑定到伪数组对象上,再通过循环将伪数组的每一项push进一个真数组再返回这个真数组。

方法3ES6Array.form()  ---有兼容性问题。
            const divs = document.querySelectorAll('div');
            console.log(divs instanceof Array);  // false
            const arr = Array.from(divs);
            console.log(arr instanceof Array);  // true