forEach和for in loop有什么区别?

时间:2019-05-14 12:14:02

标签: javascript angular foreach for-in-loop

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

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

每个代码-

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 (var key in currentStateValue){
        authService.isAuthorizedRole(key).then(function(permissionView) {
          if (permissionView == true) {
            currentStateValue[key] = true;
            console.log(currentStateValue);
          }
        });
      }

显示错误的结果

Object { dashboard: false, brandplay: true }

1 个答案:

答案 0 :(得分:0)

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对象,例如添加自定义属性或方法。