【问题标题】:What is the different between forEach and for in loop?forEach 和 for in 循环有什么区别?
【发布时间】:2019-10-01 11:14:39
【问题描述】:

我有一个使用 forEach 和 for in 循环的以下代码。实际上,当我使用 forEach 获得正确的结果以及尝试在循环中使用 for 获得错误的结果时。那么 for in 循环代码有什么问题。

var currentStateValue = { dashboard: false, brandplay: false };

ForEach 代码 -

angular.forEach(currentStateValue, function(value, key) {
      authService.isAuthorizedRole(key).then(function(permissionView) {
        if (permissionView == true) {
          currentStateValue[key] = true;
          console.log(currentStateValue);
        }
      });
    });

显示正确的结果

Object { dashboard: true, brandplay: false }

但是当我在循环中使用for时

for (var key in currentStateValue){
        authService.isAuthorizedRole(key).then(function(permissionView) {
          if (permissionView == true) {
            currentStateValue[key] = true;
            console.log(currentStateValue);
          }
        });
      }

显示错误的结果

Object { dashboard: false, brandplay: true }

【问题讨论】:

  • for...in 循环总是去最后一个对象并改变值

标签: javascript angular foreach for-in-loop


【解决方案1】:

documentation 中所述,它们说明了循环方法之间的区别:

var arr = [3, 5, 7];
arr.foo = 'hello';

for (var i in arr) {
   console.log(i); // logs "0", "1", "2", "foo"
}
// Where i will log the position in the list

for (var i of arr) {
   console.log(i); // logs 3, 5, 7
}
// Where i will log the actual value of the position in the list

var array1 = ['a', 'b', 'c'];

arr.forEach((element) => {
   console.log(element); // logs 3, 5, 7
});

forEach() 方法对每个数组执行一次提供的函数 元素。

直接来自文档

for...in 语句在所有 对象的可枚举属性。对于每个不同的属性, JavaScript 执行指定的语句。 [...] 尽管将其用作迭代 Array 的方法可能很诱人 元素,for...in 语句 将返回您的名称 除了数字索引之外的用户定义属性。这是您的问题)因此它是 最好使用带有数字索引的传统 for 循环 遍历数组,因为 for...in 语句遍历 除了数组元素之外的用户定义属性,如果您 修改 Array 对象,例如添加自定义属性或方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-05
    • 1970-01-01
    • 2012-06-11
    • 2015-02-25
    • 1970-01-01
    • 2011-04-01
    相关资源
    最近更新 更多