繁体   English   中英

如何处理消息“声明了‘变量’但从未读取其值。”

[英]What to do with the message " 'variable' is declared but its value is never read."

我正在研究一个函数,它接受 2 个整数并返回它们之间(包括)每个数字的总和。

我还希望它在第一个整数x大于第二个y ,为此我写了这个:

if (x > y) {
  let temp = x;
  x = y;
  y = x;
}

但是,我在 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; 
}

由于您只是设置值而不是使用变量,这就是它显示该消息的原因。

你可能想要下面的代码

if (x > y) {
        let temp = x;
        x = y;
        y = temp;
    }

您不需要临时变量来交换变量值,只需使用解构赋值

 let x = 10; let y = 7; if (x > y) { [x, y] = [y, x]; } console.log('x =', x); console.log('y =', y);

暂无
暂无

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

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