JavaScript - 嵌套forEach中的变量循环到undefined

时间:2017-04-23 16:02:41

标签: javascript

我试图在第二个for循环中获取this.userId的值,它通过undefined。 看看下面的代码:

 //the following variable gets undefined inside the second for loop
  this.userId = localStorage.getItem('userId');

  this.reviews.forEach(function(element1){

    element1.usersWhoLike.forEach(function(element2) {

   if(element2 == this.userId){
       //this throughs undefined !!
       console.log('UserID is : ',this.userId)
   }

  });

  });

3 个答案:

答案 0 :(得分:1)

你错过了forEach里面的功能范围 我们试试吧:

this.reviews.forEach(function(element1){

    element1.usersWhoLike.forEach(function(element2) {

   if(element2 == userId){
       //this throughs undefined !!
       console.log('UserID is : ',this.userId)
   }

  }, this);

  }, this);

答案 1 :(得分:0)

this.userId在第二个中指的是函数范围本身。尝试添加var self作为参考

    this.userId = localStorage.getItem('userId');

    var self = this; // Referencing
    this.reviews.forEach(function(element1){

        element1.usersWhoLike.forEach(function(element2) {

            if(element2 == userId){
                //this throughs undefined !!
                console.log('UserID is : ',self.userId)
            }

        });

    });

答案 2 :(得分:0)

this.userId = localStorage.getItem('userId');

将此行置于第一个循环