如何使负输出真正变为负?

时间:2019-04-24 12:48:15

标签: javascript

我这样计算i=0; while (i < a.length){ if(a[i] <= x) { return i; i++; } else { return -1; } } return i;

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

为什么?以及如何纠正?

5 个答案:

答案 0 :(得分:4)

似乎正确的运算符是> =而不是=>

答案 1 :(得分:1)

js中的=>是箭头功能,请参见arrow function

您应该使用此

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

答案 2 :(得分:0)

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

答案 3 :(得分: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))

答案 4 :(得分:0)

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

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