简体   繁体   English

递归函数中的变量声明

[英]Variable declaration in recursion function

I spent a long time trying to complete this function only to see that the syntax i was trying was not being accepted. 我花了很长时间尝试完成此功能,只是发现我尝试的语法没有被接受。

The countSheep function in code academy tells you to complete the function and gives you a newNumber variable that seems to not be defined in the local scope. 代码学院中的countSheep函数告诉您完成该功能,并为您提供一个newNumber变量,该变量似乎未在本地范围内定义。 So I tried to give it the "var" keyword. 因此,我尝试为其指定“ var”关键字。 For some reason I can't understand the var keyword was not necessary and in order to complete the function and get it to pass the test I had to use the following: 由于某种原因,我无法理解var关键字不是必需的,并且为了完成功能并使它通过测试,我必须使用以下命令:

as opposed to defining the variable I just used newNumber = number -1; 与定义变量相反,我只是使用newNumber = number -1; // can also be written as newNumber -= 1; //也可以写成newNumber-= 1; passed newNumber to the function 将newNumber传递给函数

OR 要么

not defined the newNumber variable and just invoke the function using n-1 as the parameter. 未定义newNumber变量,而只是使用n-1作为参数调用该函数。

Here is the code that code academy gave us to solve. 这是代码学院提供给我们解决的代码。

 function countSheep(number) { if (number === 0) { console.log("Zzzzzz");// Put your base case here } else { console.log("Another sheep jumps over the fence."); // Define the variable newNumber as // 1 less than the input variable number newNumber = number - 1; // Recursively call the function // with newNumber as the parameter countSheep(newNumber); } } 

Can someone please tell me why the var keyword is not necessary inside of the function to define the newNumber variable. 有人可以告诉我为什么在函数内部不需要var关键字来定义newNumber变量。 I appreciate it. 我很感激。

if you declare newNumber using var it is only accessable on the scope of else block 如果使用var声明newNumber ,则只能在else块的范围内访问

.But if you don`t use var it will not be local,means can be accessed on the outer scope**(countSheep).** 但是,如果您不使用var ,它将不是本地的,则可以在外部范围**(countSheep)上访问方法。**

newNumber is a global variable that means, it is assigned to the global object. newNumber是一个全局变量,表示已分配给全局对象。 In browsers this is the window object: 在浏览器中,这是window对象:

 function f(x) { y = x; } console.log(window.y); f(123); console.log(window.y); 

To create a local variable that is only accessible within the function, use var : 要创建只能在函数中访问的局部变量,请使用var

 function f(x) { var y = x; console.log("within f:", y); } f(123); console.log("outside f:", window.y); 

To create a local variable that is only accessible within its surrounding block, use let or const : 要创建只能在其周围的块中访问的局部变量,请使用letconst

 function f(x) { { let y = x; console.log("inside block", y); } try {y} catch (e) {console.log("outside block:", e.message)} } f(123); 

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

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