简述js中 for in 与 for of 区别

    科技2022-07-13  132

     for in、for of的区别:

    遍历数组:

    let arr = [1,2,3,4,"d","f","g",""," "]; for(let val of arr){ console.log(val); } for(let index in arr){ console.log(index,arr[index]); }

    控制台结果如下:

    遍历对象: 

    let obj = { "name":"Ghui", "sex":0, "age":24, say:function say(){ console.log(this.name + "说:我是" + this.name); } } for(let key in obj){ console.log(key,obj[key]) } for(let index of obj){ console.log(index) }

    控制台结果如下: 

    遍历字符串

    let str = "Ghui"; for(let strindex in str){ console.log(s) } for(let string of str){ console.log(string) }

    控制台结果如下:

    总结:

    for in 取 key,for of 取 value

    for of 只能用于数组遍历,for in还可以遍历对象

    Processed: 0.009, SQL: 8