1

JavaScript for/of, for/in 介绍

 2 years ago
source link: https://foofish.net/JavaScript-for-of-for-in.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

JavaScript for/of, for/in 介绍

By 刘志军, 2021-09-22, 分类: javascript



在 JavaScript中,for 循环有几种常见的写法

第一种最常规的写法

nums = [1,2,3,4]

for (let i=0; i<nums.length; i++){
    console.log(nums[i])
}

第二种: for/of 写法,是ES6开始有的语法, 可以直接迭代出数组中的每个元素,无需通过下标索引位置来获取元素,其实只要是可迭代对象,都可以使用 for/of 。

for (let item of nums){
    console.log(item)
}

第三种写法 for/in 写法, 不像for/of 必须是可迭代对象,for/in 可迭代任意对象。循环迭代对象的属性名。如果是数组,迭代的值是数组的下标索引,和原始那个for是一样的。

let p = {name:"zhang", age:10}

for(let key in p){
    console.log(p[key])
}
zhang
10
for (let index of nums){
    console.log(nums[index])
}

for/in 并不能枚举迭代对象的所有是属性,比如符号属性无法枚举

for/of 和 for/in 写法在定义变量的时候,也可以使用 const 关键字,const声明的是一次循环迭代期间的常量值。

有问题可以扫描二维码和我交流

关注公众号「Python之禅」,回复「1024」免费获取Python资源

python之禅

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK