如何使负输出真的消极? [关闭]

问题描述 投票:1回答:5

我像这样计算一个var

var difference = new - old;

这会输出正数或负数。

然后:

if (difference => 2) {
  text = "2 or more";
} else if (difference < -1) {
  text = "more than 1 behind;
} 

使用此代码,即使difference输出为-5000,我仍然得到2 or more。而它应该是even less than 1

为什么?以及如何纠正?

javascript
5个回答
4
投票

似乎右边的运算符是> =而不是=>


1
投票

=>是js中的箭头函数,参见arrow function

你应该用它

if (difference >= 2) {
      text = "2 or more";
    } else if (difference < -1) {
      text = "more than 1 behind;
    } 

0
投票
 if (difference >= 2) {
  text = "2 or more";
} else if (difference < -1) {
  text = "more than 1 behind;
} 

0
投票

这是你的代码插入一个函数。

确保使用不等式>=的数学符号。

function check(difference){
text = "";
if (difference >= 2) {
  text = "2 or more";
} else if (difference < -1) {
  text = "more than 1 behind";
}
return difference + ": " + text;
}


console.log(check(-3))
console.log(check(-2))
console.log(check(-1))
console.log(check(0))
console.log(check(1))
console.log(check(2))
console.log(check(3))
console.log(check(4))
console.log(check(5))

0
投票

使用比较运算符的正确方法是> =

if (difference >= 2) {
  text = "2 or more";
} else if (difference < -1) {
  text = "more than 1 behind;
} 

推荐问答