JavaScript 替代“for each”循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12637289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:54:50  来源:igfitidea点击:

JavaScript alternative to "for each" loop

javascriptfor-loopforeach

提问by user1537366

According to the MDN page at for each...in loop, this construct is deprecated. Is there an alternative that does exactly the same thing? The for...of loopdoes not iterate over non-integer (own enumerable) properties. If there isn't an alternative, why did they deprecate it then?

根据for each...in loop的 MDN 页面,不推荐使用此构造。有没有完全相同的替代方法?在对...循环的不叠代非整数(自己的枚举)的属性。如果没有替代方案,他们为什么要弃用它呢?

采纳答案by Quentin

Is there an alternative that does exactly the same thing?

有没有完全相同的替代方法?

A for ... inloop in which the first thing you do in the block of code is to copy foo[propertyname]to a variable.

for ... in您在代码块中做的第一件事是复制foo[propertyname]到变量的循环。

回答by Denys Séguret

To iterate over all the properties of an object obj, you may do this :

要遍历对象的所有属性obj,您可以这样做:

for (var key in obj) {
   console.log(key, obj[key]);
}

If you want to avoid inherited properties, you may do this :

如果你想避免继承属性,你可以这样做:

for (var key in obj) {
   if (!obj.hasOwnProperty(key)) continue;
   console.log(key, obj[key]);
}

回答by Renaat De Muynck

You can make use of the new ECMAScript 5th Editionfunctions:

您可以使用新的ECMAScript 第 5 版函数:

Object.keys(obj).forEach(function (key) {
    console.log(key, obj[key]);
});