我正在研究一个函数,它接受 2 个整数并返回它们之间(包括)每个数字的总和。
我也希望它在第一个整数x大于第二个时工作y,为此我写了这个:
if (x > y) {
let temp = x;
x = y;
y = x;
}
Run Code Online (Sandbox Code Playgroud)
但是,我在 Visual Studio Code 上收到此消息:
'temp' 被声明,但它的值永远不会被读取。
问题是什么?
此外,这是完整的脚本:
const sumAll = function( x , y ) {
if (x !== Math.abs(x) || y !== Math.abs(y)) return ("ERROR");
if (typeof x !== "number" || typeof y !== "number") return ("ERROR");
if (x > y) {
let temp = x;
x = y;
y = x;
}
let finalSum = 0;
for (i = x; i <= y; i++){
finalSum += i;
}
return finalSum;
}
Run Code Online (Sandbox Code Playgroud)
由于您只是设置值而不是使用变量,这就是它显示该消息的原因。
你可能想要下面的代码
if (x > y) {
let temp = x;
x = y;
y = temp;
}
Run Code Online (Sandbox Code Playgroud)