Javascript Switch语句无法正常运行

时间:2016-11-09 04:31:56

标签: javascript node.js

我有一种情况,我将得到一个小数,我需要根据结果存储不同的对象,我想使用Switch / case语句来做到这一点,但它没有表现我的期望。

这是代码......

var spread = high - low;
var closeDiff = close - low;
var answer = closeDiff / spread;

switch(answer <= .3999) {
    case (answer <= .3999):
    singleEntry["percentClose"] = answer;
    singleEntry["supportDay"] = false;
    console.log("answer <= .39999");
    break;
    case (answer > .95):
    singleEntry["percentClose"] = answer;
    singleEntry["supportDay"] = true;
    singleEntry["peakClose"] = true;
    console.log("answer > .95");
    break;
    default:
    singleEntry["percentClose"] = answer;
    singleEntry["supportDay"] = true;
    console.log("answer default");
}

即使answer不低于.3999,它也始终默认为第一种情况。我有7500个计算要做,它总是控制下面的代码。

console.log("answer <= .39999");

那么这笔交易是什么?

3 个答案:

答案 0 :(得分:1)

switch不适合您正在做的事情。

if (answer <= .3999) {
    singleEntry["percentClose"] = answer;
    singleEntry["supportDay"] = false;
    console.log("answer <= .39999");    
}
else if (answer > .95) {
    singleEntry["percentClose"] = answer;
    singleEntry["supportDay"] = true;
    singleEntry["peakClose"] = true;
    console.log("answer > .95");    
}
else {
    singleEntry["percentClose"] = answer;
    singleEntry["supportDay"] = true;
    console.log("answer default");
}

switch语句对于在表达式的几个可能的离散结果之一中进行选择很有用。在您的情况下,您有一个可能具有一个或另一个范围内的值的变量,因此根本不是相同的情况。

答案 1 :(得分:1)

首先要了解switch语句。试着研究这个 JavaScript Switch Statement

switch(expression) {
case n:
    code block
    break;
case n:
    code block
    break;
default:
    default code block

}

答案 2 :(得分:-2)

您误解了switch语句的使用。它用于将表达式的真实值与案例进行比较。但是,如果你想坚持这种格式,你可以这样做。

var spread = high - low;
var closeDiff = close - low;
var answer = closeDiff / spread;

switch(true){
    case (answer <= .3999):
        singleEntry["percentClose"] = answer;
        singleEntry["supportDay"] = false;
        console.log("answer <= .39999");
        break;
    case (answer > .95):
        singleEntry["percentClose"] = answer;
        singleEntry["supportDay"] = true;
        singleEntry["peakClose"] = true;
        console.log("answer > .95");
        break;
    default:
        singleEntry["percentClose"] = answer;
        singleEntry["supportDay"] = true;
        console.log("answer default");                                          
    }

这会将true条件与第一个计算结果为true的案例表达式匹配。