javascript中的for...of循环

for...of循环

这个直接看代码吧

1.遍历数组

        var arr = [1,2,3,4,5];
        
        for(let val of arr.values()){
            console.log(val)
        }
        //1
        //2
        //3
        //4
        //5

2.遍历索引

        var arr = [1,2,3,4,5];

        for(let index of arr.keys()){
            console.log(index)
        }
    
        //0
        //1
        //2
        //3
        //4

3.遍历值和索引

        var arr = [1,2,3,4,5];

        for(let item of arr.entries()){
            console.log(item)
        }
        //第一个是索引,第二个是值
        // [0, 1]
        // [1, 2]
        // [2, 3]
        // [3, 4]
        // [4, 5]

4.上面的结果看起来和平时看的不一样,看下面

        var arr = [1,2,3,4,5];

        for(let [key,val] of arr.entries()){
            console.log(key,val)
        }

        // 0 1
        // 1 2
        // 2 3
        // 3 4
        // 4 5

在for...of中 

数组多了三个属性

arr.values()         //数组的值

arr.keys()            //数组的下标

arr.entries()         //数组的某一项

for...of 和for...in 的区别

for...in语句以任意顺序迭代对象的可枚举属性(可以枚举属性)

for...of语句迭代可迭代对象定义为迭代的数据(只枚举数据)

        var arr = [1,2,3,4,5];
        //设置数组,并给数组的原型上添加属性
        Array.prototype.name = "Name";


        //for...of方法打印
        for(let val of arr){
            console.log(val)
        }
        // 1,2,3,4,5


        //for...in方法打印
        //1,2,3,4,5,name
        for(let item in arr){
            console.log(arr[item])
        }

for...of 的实用案例

arguments是个类数组对象,通常先要将其转换为数组才能遍历,但for...of可以直接遍历 

        function sum() {
            let sum = 0
            for (let num of arguments) {
                sum += num
            }
            console.log(sum);        //15
        }

        sum(1, 2, 3, 4, 5)

遍历字符串

let name = 'Asher';

for (let char of name) {

console.log(char); //A s h e r

}

猜你喜欢

转载自blog.csdn.net/qq_41702660/article/details/81952128