JavaScript遍历数组的方法

下面由浅入深讲解遍历数组的方法,着急的读者可以直接看方法三和方法四。可以快速使用。
查看数组的查找方法可点击此链接。

需求:要求遍历数组

方法一:利用传统循环来遍历数组
let arr = [1, 3, 5, 7]//定义数组,数组本质是对象
        for (let i = 0; i < arr.length; i++){
            console.log(arr[i]);
        }
方法二:利用高级循环for…in来遍历(不推荐,讲明理由)

在企业开发中不推荐使用for…in循环来遍历数组,因为for…in循环是专门用来遍历对象的,是遍历无序的。而数组是有序的。

    for (let key in arr){//将索引依次赋值给key
        console.log(arr[key]);
    }
    //注意点:对象中的属性是无序的
    //for...in循环是专门用来遍历对象的,但是对象的属性无序的。因此for...in循环专门用于遍历无序的东西,所以不推荐使用forin循环来遍历数组。

//https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/for…in#%E6%95%B0%E7%BB%84%E8%BF%AD%E4%BB%A3%E5%92%8C_for…in

证明对象的属性是无序的:

  function Person() {
            this.name = "GG";
            this.age = 3;
            this.score = 99;
        }
        let p = new Person();//通过构造函数创建对象
        console.log(p);

结果:
在这里插入图片描述

方法三、利用ES6中推出的for… of循环遍历数组
        for (let value of arr){
         console.log(value);
     }

方法四、还可以利用Array对象的forEach方法来遍历数组

forEach方法会自动调用传入函数。
每次调用都会将当前遍历到的元素、当前遍历到的索引和当前遍历的数组传递给这个函数。

 arr.forEach(function (currentValue, currentIndex, currentArray) {
            // console.log(currentValue, currentIndex, currentArray);//当前遍历到的元素取值,元素索引,被遍历的数组
            console.log(currentValue);
        })

forEach实现方法

        Array.prototype.myForEach = function (fn) {
            for (let i = 0; i < this.length; i++) {//this:谁调用就是谁。arr数组调用的就是这个数组。this === [1, 3, 5, 7]
                fn(this[i], i, this);
            }
        };
        arr.myForEach(function (currentValue, currentIndex, currentArray) {
            console.log(currentValue, currentIndex, currentArray);
        })

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Cao_Mary/article/details/89680214