第3章函数包含以下代码段:
const power = function(base, exponent) {
let result = 1;
for(let count = 0; count < exponent; count++) {
result *= base;
}
return result;
};
console.log(power(2, 10));
// 1024
有人可以逐行解释代码中发生了什么,我对let result = 1最困惑。谢谢!
答案 0 :(得分:0)
在第一行中,您声明一个变量result
。但是,它是用let
而不是var
声明的。 Let与var相似,除了它不能在定义的块(包括函数,循环和条件语句)之外访问。并且由于它在这里的函数中,所以第一行等效于:
var result = 1;
在第二行:
for (let count = 0; count < exponent; count++) {}
您要遍历exponent
-循环{}
中的代码将被执行exponent
次。
第三行:
result *= base;
您要将result
和base
相乘,并将值分配给result
。该行等效于:
result = result * base;
最后一行:
return result;
此行停止函数并返回result
。 return表示每当调用一个函数时,实际上都将其替换为返回值(如此行所示):
console.log(power(2, 10));
这将使用参数2和10调用power()
,并将返回的值记录到控制台。
答案 1 :(得分:0)
此示例是在JavaScript中构建和执行指数函数的简单方法。
也就是说,我们知道下面的内容将在伪代码中创建类似以下内容的东西:
print the result of (number to the power of some other number)
代码演练:
// initialize a constant variable named 'power' as a function declaration with two arguments, 'base' and 'exponent' which will be used inside the function
const power = function(base, exponent) {
// declare and initialize variable called 'result' and set it with value of 1
// why this is 1, is because any number to the power of 1 is itself, so rather than setting this to 0, this must be 1 to ensure that the exponential function works accurately
let result = 1;
// let count = 0; this will initialize a variable named count to be used within the loop
// count < exponent; this is the conditional statement, it means that the loop will continue looping until the condition is met, meaning loop until 'count' is no longer less than 'exponent'
// count++; this increments the value of the initial variable, in this case 'count' for every trip through the loop for the duration that the condition statement remains true
for (let count = 0; count < exponent; count++) {
// multiply the 'result' variable by the 'base' variable and set it as the new value of the 'result' variable
result *= base;
}
// return the 'result' variable so that it is now available outside of the function
return result;
};
// pass in the 'base' and 'exponent' arguments for the function 'power' in order to get the value (effectively, 2^10), and then print this value to the console
console.log(power(2, 10));
// 1024