[英]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.