简体   繁体   English

除了 scope 之外,在循环内部声明变量与在外部声明变量有什么区别?

[英]Besides scope, what's the difference between declaring a variable inside a loop vs outside?

While studying JS, I came across this problem/solution in CodeWars.在学习 JS 时,我在 CodeWars 中遇到了这个问题/解决方案。

Problem: Create a function that turns a string into a "Mexican Wave."问题:创建一个 function 将字符串变成“墨西哥波”。 For example: "hello" ==> ['Hello', 'hEllo', 'heLlo', 'helLo', 'hellO'] .例如: "hello" ==> ['Hello', 'hEllo', 'heLlo', 'helLo', 'hellO']

Solution (splitStr INSIDE loop):解决方案(splitStr INSIDE 循环):

function wave(str) {
  let waveArr = [];
  for (let i = 0; i < str.length; i++) {
    const splitStr = str.split(""); // INSIDE loop
    if (splitStr[i] !== " ") {
      splitStr[i] = splitStr[i].toUpperCase();
      waveArr.push(splitStr.join(""));
    }
  }
  console.log(waveArr);
  return waveArr;
}
wave("hello");
// returns ['Hello', 'hEllo', 'heLlo', 'helLo', 'hellO']

I noticed the function returns something different if splitStr is declared OUTSIDE the loop: ['Hello', 'HEllo', 'HELlo', 'HELLo', 'HELLO'] .我注意到function如果在循环外声明splitStr会返回不同的内容: ['Hello', 'HEllo', 'HELlo', 'HELLo', 'HELLO'] Instead of only capitalizing one letter per iteration, it capitalizes multiple.它不是每次迭代只大写一个字母,而是大写多个。 Why does this happen?为什么会这样?

splitStr OUTSIDE loop: splitStr 外部循环:

function wave(str) {
  let waveArr = [];
  const splitStr = str.split(""); // OUTSIDE loop
  for (let i = 0; i < str.length; i++) {
    if (splitStr[i] !== " ") {
      splitStr[i] = splitStr[i].toUpperCase();
      waveArr.push(splitStr.join(""));
    }
  }
  console.log(waveArr);
  return waveArr;
}
wave("hello");
// returns ['Hello', 'HEllo', 'HELlo', 'HELLo', 'HELLO']

When a variable is declared outside of a loop it's state is maintained for all loop instances.当一个变量在循环外声明时,它的 state 会为所有循环实例维护。 Take a counter for example:以计数器为例:

var counter = 0;
for(var i=0;i<10;i++){
    counter = counter + 1;
    console.log(counter);
}

since we declared the variable counter outside of the loop, it's value is maintained for each instance of the loop resulting in it incrementing up.因为我们在循环之外声明了变量counter ,所以它的值会为循环的每个实例保持不变,从而导致它递增。

For the same example if we declare counter within the loop:对于同样的例子,如果我们在循环中声明计数器:

for(var i=0;i<10;i++){
    var counter = 0;
    counter = counter + 1;
    console.log(counter);
}

the counter variable will be destroyed and recreated every instance of the loop. counter变量将被销毁并重新创建循环的每个实例。 This results in the log statement always printing 1 .这导致日志语句总是打印1

So to summarize, variables created within a loop will only exist for the duration of that instance of the loop, while variables declared outside of the loop will continue to exist for all instances of the loop.总而言之,在循环中创建的变量只会在该循环实例的持续时间内存在,而在循环之外声明的变量将继续存在于循环的所有实例中。

暂无
暂无

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

相关问题 在for循环和外部循环中声明变量有什么区别? - What is the difference between declaring variable in for loop and an outside loop? TypeScript:在构造函数内部和外部声明变量有什么区别? - TypeScript: What is the difference between declaring variables inside the constructor and outside of it? for 循环用于在其中声明变量但不在全局范围内 - The for loop works on declaring the variable inside it but not in the global scope 在类外部调用函数与在内部调用函数有什么区别? - What is the difference between invoking a function outside of class vs inside of it? 在组件的外部声明一个函数有什么区别吗? - Is there any difference between declaring a function inside our outside the component's body? 将结果变量保持在 for 循环(Javascript)之外有什么区别? - what is the difference between keeping result variable outside the for loop (Javascript)? 使用var与函数声明javascript对象有什么区别? - What is the difference between declaring javascript objects with var vs. with function? 将promise包装在函数中和在变量内部声明之间的区别 - Difference between wrapping a promise in a function and declaring it inside a variable 在 Vue 选项中定义模板与在外部定义模板有什么区别? - What is the difference between defining your template inside Vue options vs outside? 使用“ new”或不使用变量声明变量之间有什么区别? - What is the difference between declaring a variable using “new” or without using it?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM