gpt4 book ai didi

javascript - 是否存在与 Python 的 for 循环等效的 JavaScript?

转载 作者:太空狗 更新时间:2023-10-29 22:15:46 24 4
gpt4 key购买 nike

所以我很失望地发现 JavaScript 的 for (var in array/object) 不等同于 pythons for var in list:

在 JavaScript 中,您正在迭代索引本身,例如

0, 
1,
2,
...

与 Python 一样,您正在迭代索引指向的值,例如

"string var at index 0", 
46,
"string var at index 2",
["array","of","values"],
...

有没有标准的 JavaScript 等同于 Python 的循环机制?

免责声明:

I am aware that the for (var in object) construct is meant to be used to iterate over keys in a dictionary and not generally over indices of an array. I am asking a specific question that pertains to use cases in which I do not care about order(or very much about speed) and just don't feel like using a while loop.

最佳答案

在下一版本的 ECMAScript(ECMAScript6 又名 Harmony)中将是 for-of construct :

for (let word of ["one", "two", "three"]) {
alert(word);
}

for-of 可用于迭代各种对象、数组、映射、集合和自定义可迭代对象。从这个意义上说,它非常接近 Python 的 for-in

关于javascript - 是否存在与 Python 的 for 循环等效的 JavaScript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27967988/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com