【问题标题】:How to correctly calculate a variable inside of a parameter [duplicate]如何正确计算参数内的变量[重复]
【发布时间】:2021-11-14 23:18:51
【问题描述】:

以下是 javascript 代码,我在托管 localhost 时使用的是 mozilla 浏览器:

var test = 1; 
    console.log ("results are as such : "+ test-1 +". What we got instead is: "+ test+2 +". Astonishing!");
//The results: ("NaN. What we got instead is: 12. Astonishing!")

执行“Console.WriteLine(”结果是这样的:“+ test-1 +”。我们得到的是:“+ test+2 +”。令人惊讶!”); 将在 C# 中完全按照我的意愿执行(在引号中显示文本,然后显示 1-1 = 0 和 1+2 = 3 的结果),我不太熟悉它在 JavaScript 中的工作原理,我在浏览时找不到任何答案。

我可以帮忙吗?

【问题讨论】:

  • TLDR:"test" - 1NaN。不知道为什么 C# 有如此疯狂的运算符优先级。
  • ... +(test-1)+ ...
  • 您需要在数学表达式周围加上括号。否则,它会对字符串和数字进行操作(在你的情况下,像一些stirng-1这样的东西),导致奇怪的结果,比如NaN。所以这样做:console.log ("results are as such : "+(test-1)+". What we got instead is: "+(test+2)+". Astonishing!");

标签: javascript


【解决方案1】:
console.log(`result are as such: ${test} - 1 = ${test - 1}. and ${test} + 2 = ${test + 2}`);

【讨论】:

    猜你喜欢
    • 2021-03-11
    • 2017-09-19
    • 2023-03-07
    • 2019-08-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-13
    • 1970-01-01
    • 2019-02-19
    相关资源
    最近更新 更多