简体   繁体   English

在for循环中将局部范围变为全局范围

[英]Making a local scope inside a for loop, into a global scope

I have been searching but I cant get a clear answer. 我一直在搜索,但无法得到明确的答案。 (I am a beginner in javascript and this is a test/practice inside the console) How can I make a local scope within a for loop, a global scope so I can then add it to variable with an array of objects. (我是javascript的初学者,这是控制台内的一种测试/做法)如何在for循环中创建局部作用域(即全局作用域),以便随后将其添加到具有对象数组的变量中。 For Example : I want the user to set how many stars(rating) a movie has inside a variable(prompt) named "stars". 例如:我希望用户设置电影在名为“ stars”的变量(提示)中有多少颗星(等级)。 Then be able to call it inside the movieDb variable inside the object/array where it says "rating :" ... using the variable stars so it can console log the stars the user inputs along with the other information. 然后,可以在对象/数组中的movieDb变量中使用“ star”变量来调用它,使用变量star来控制台记录用户输入的star以及其他信息。 Is this allowed or is there a different approach? 这是允许的还是有其他方法?

 var movieDb =[
  {
    haswatched : "i",
    title : "In Burges",
    rating : stars,
  },
  {
    haswatched : "i",
    title : "Frozen",
    rating : stars,
  },
  {
    haswatched : "i",
    title : "Mad Max",
    rating : stars,
  },
]

for (var i = 0; i < movieDb.length ; i++) {
  var w = prompt("did you watch the movie?")
  if (w === 'yes'){//first IF
    movieDb[i].haswatched = "you have watched";
    var r = prompt("would you like to rate us?");
        if (r === "yes") {//nested in first IF
            var stars = prompt("Enters Stars");
            alert("Thanks for rating & Watching!")
        } else if(r === "no"){ //nested in second IF
            alert("You did not rate, Thanks for watching!")
        }
  }
  else if (w === "no"){ //first ELSE IF
    movieDb[i].haswatched = "you have not seen";
  }
console.log(movieDb[i].haswatched + " " + "\""+movieDb[i].title+"\"" + " -" + movieDb[i].rating);
}'

var in javascript have function scope. javascript中的var具有功能范围。 So even if you define it inside for loop they will be available outside the loop. 因此,即使您在for循环内定义它,它们也将在循环外可用。 If you do console.log before the loop, the value will be undefined and if you do it after the loop, the value will be last value available inside the loop. 如果在循环之前执行console.log,则该值将是未定义的;如果在循环之后执行,则该值将是循环内可用的最后一个值。 To make things block scoped ( local scope inside the loop ), use let & const. 要使事物成为块作用域(循环内的局部作用域),请使用let&const。 They are available in ES6 and with all the major browsers support them. 它们在ES6中可用,并且所有主要的浏览器都支持它们。

Hope this will help 希望这会有所帮助

Happy Learning 快乐学习

Vatsal 瓦萨尔

I'm not sure I understood quite well your question so don't hesitate to correct me if I say something stupid or answer to a question you didn't ask. 我不确定我是否很好地理解了您的问题,因此,如果我说了些愚蠢的话或回答了您没有问过的问题,请立即纠正我。

The best way to define a variable inside a for loop scope is to declare it with let . 在for循环范围内定义变量的最佳方法是使用let进行声明。

var i = "aaa";

for (let i = 0; i < 10; i++) {
    console.log(i); // => 0...9
}

console.log(i); // => "aaa"

I think the problem you are facing is that stars doesn't exist. 我认为您面临的问题是stars不存在。
You can either set it to false or null (or whatever value), and then set it to the number you get with the prompt, or just set it when you have the value : 您可以将其设置为falsenull (或任何值),然后将其设置为在提示符下获得的数字,或者仅在具有值时设置它:

{
haswatched : "i",
title : "In Burges"
}

...

movieDb[i].stars = stars;

I don't know if it is quicker to set it to an Int value at first, but that would be such a tiny improvement in this case that I'm not sure it would matter much. 我不知道起初将它设置为Int值是否更快,但是在这种情况下,这将是很小的改进,我不确定它是否有太大关系。

Hope it helps 希望能帮助到你

Edit : 编辑:

About let scope inside a loop, here's an example : 关于let作用域内循环,这是一个示例:

<ul>
    <li>a</li>
    <li>b</li>
    <li>c</li>
    <li>d</li>
    <li>e</li>
</ul>

<script>
var lis = document.querySelectorAll('li');
for (let i = 0; i < lis.length; i++) {
    lis[i].addEventListener('click', function(){
        console.log(i);
    });
}
</script>

When clicking on li, show position (from 0 to 4) although : 单击li时,显示位置(从0到4),尽管:

<script>
var lis = document.querySelectorAll('li');
for (var i = 0; i < lis.length; i++) {
    lis[i].addEventListener('click', function(){
        console.log(i);
    });
}
</script>

Would display 5 (i is incremented before leaving the loop) 将显示5(i在离开循环之前递增)

I think if I understand what you are trying to achieve, this should help ... 我认为,如果我了解您要达到的目标,这应该会有所帮助...

var movieDb = [
    {
    haswatched : "i",
    title : "In Burges",
    rating : 0,
  },
  {
    haswatched : "i",
    title : "Frozen",
    rating : 0,
  },
  {
    haswatched : "i",
    title : "Mad Max",
    rating : 0,
  },
];

for (var i = 0; i < movieDb.length ; i++) {
   var w = prompt("did you watch the movie " + movieDb[i].title + "?")
   if (w === 'yes'){//first IF
      movieDb[i].haswatched = "you have watched";
      var r = prompt("would you like to rate us?");
      if (r === "yes") {//nested in first IF
          var stars = prompt("Enters Stars");
          movieDb[i].rating = stars;
          alert("Thanks for rating & Watching!")
      } else if(r === "no"){ //nested in second IF
          alert("You did not rate, Thanks for watching!")
      }
   } else if (w === "no"){ //first ELSE IF
      movieDb[i].haswatched = "you have not seen";
   }
}

console.log(movieDb);

https://jsfiddle.net/ramsmxms/ https://jsfiddle.net/ramsmxms/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM