0

我在处理来自 json 请求的一些数字时遇到问题。根据结果​​,我试图输出一些不同的 HTML。具体问题是当我来检查一个数字是否大于-1但小于6时。代码摘录如下……</p>

else if(parseInt(myvariable, 10) < -1) {
//this is where one thing happens
}
else if(parseInt(myvariable, 10) > -1) {
//Something else happens here
}
else if(parseInt(myvariable, 10) > 6) {
//This is where the third thing should happen, but doesn't?
}

似乎尽管值为 7 或 70,但第二个“else if”已达到极限。

有没有一种方法可以检查该数字是否大于 -1 但小于 6,以便继续执行下一个条件语句。

我猜(就像我之前的问题一样)有一个非常简单的答案,所以请原谅我的天真。

提前致谢。

4

5 回答 5

0

if 条件错误。让我们考虑一下:myvariable 是 7。

在您的代码中会发生:

else if(parseInt(myvariable, 10) < -1) {
//this is where one thing happens
}
else if(parseInt(myvariable, 10) > -1) {
**// HERE THE CONDITION IS TRUE, BECAUSE 7 > -1**
}
else if(parseInt(myvariable, 10) > 6) {
// This is where the third thing should happen, but doesn't?
}

您可以将其更改为

else if(parseInt(myvariable, 10) < -1) {
//this is where one thing happens
}
else if(parseInt(myvariable, 10) > 6) {
// This is where the third thing should happen, but doesn't?
}
else if(parseInt(myvariable, 10) > -1) {
 // Moved
}

为了让它工作...

于 2012-07-15T09:59:38.883 回答
0

仅在发现一个为真之前执行条件。

换句话说,您需要重新调整他们的订单或收紧他们以使您当前的订单正常工作。

7 高于 -1,因此第二个条件解析为真。所以对于 7,第 3 个条件是不需要的。

if(parseInt(myvariable, 10) < -1) {
    //number is less than -1
}
else if(parseInt(myvariable, 10) > 6) {
    //number is above 6
}
else {
    //neither, so must be inbetween -1 an 6
}
于 2012-07-15T10:00:39.083 回答
0

是的,因为你写的任何大于 -1 的数字都不会抛出第三个代码块,它会抛出第二个代码块,正如你所说“数字大于 -1 但小于 6 ”,你可以简单地这样做:

else if(parseInt(myvariable, 10) < -1) {
//this is where one thing happens
}
else if(parseInt(myvariable, 10) > -1 && parseInt(myvariable, 10) < 6) {
//Something else happens here
}
于 2012-07-15T10:02:15.007 回答
0

另一种解决方案是更改第二行:

else if(parseInt(myvariable, 10) > -1)

至:

else if(parseInt(myvariable, 10) <= 6)

有很多方法可以写这个。

于 2012-07-15T10:05:59.710 回答
0

我想你可以很容易地做到这一点,做这样的事情:

考虑到您的变量值为(7):

else if(parseInt(myVariable, 10) &lt; -1) {
//this is where one thing happens
}
else if(parseInt(myVariable, 10) > -1) {
//now 'myVariable' is greater than -1, then let's check if it is greater than 6
if(parseInt(myVariable, 10) > 6) {
//this where what you should do if 'myVariable' greater than -1 AND greater than 6
}
}
于 2012-07-15T10:18:13.273 回答