条件运算符无法按预期在javascript中工作

时间:2019-05-06 07:03:30

标签: javascript jquery arrays object conditional

以下条件运算符未按预期工作 我已将条件包括在基于方案中。

如果没有src或tar匹配,则应为rate = 0

如果src存在于arr中且为SGD,而src存在于arr中且为SGD(反之亦然),则速率为0.4

如果src存在于arr中且为"EUR" || "GBP" || "USD",而tar存在于arr中且"SGD",则反之亦然,比率为0.3

如果arr中存在src,而arr中存在tar,则速率应为0.5

场景:

(src==="SGD" and tar==="AUD") or (src==="AUD" && tar==="SGD")  => rate="0.4"
src === "SGD") and (tar === "EUR" or "GBP" or "USD") => rate=0.3
(src==`arr` values  and tar==`arr` values)=> rate=0.5 
(src no match arr && tar no match arr)=> rate=0
var arr =["AED","BGN","CAD","CHF","CZK","DKK","HKD","HUF","ILS","INR",
       "JPY","MXN","NOK","NZD","PLN","QAR","RON","SAR","SEK","THB","TRY","ZAR"];

I tried , but not working if src="SGD" and tar="CNY" it should rate =0
var res=
      ((src === "SGD" && tar === "AUD") || (src  === "AUD" && tar === "SGD"))?
      rate = 0.4 : 
      ((src === "SGD" && (tar === "EUR" || "GBP" || "USD")) ||
      ((src === "EUR" || "GBP" || "USD") && tar === "SGD"))?
      rate = 0.3:
      (src.indexOf(arr)!=-1 && tar.indexOf(arr)!=-1) ?
      rate = 0.5 : 
     rate=0;


3 个答案:

答案 0 :(得分:1)

您使用了您或您的条件而没有检查变量。就像"USD" || "GBP"一样,它将始终返回true

,您还有另一个错误应检查,例如array.index(variable)。但是您像

src.indexOf(arr)!=-1 && tar.indexOf(arr)!=-1

我添加了一个演示代码段,请检查它。

我使用了这种特殊条件。

(tar === "EUR" || tar === "GBP" || tar === "USD"))

var tar = "DKK";
var src = "AUD";
var arr =["AUD","DKK","AED","BGN","CAD","CHF","CZK","DKK","HKD","HUF","ILS","INR",
       "JPY","MXN","NOK","NZD","PLN","QAR","RON","SAR","SEK","THB","TRY","ZAR"];
var res=
      ((src === "SGD" && tar === "AUD") || (src  === "AUD" && tar === "SGD"))?
      rate = 0.4 : 
      ((src === "SGD" && (tar === "EUR" || tar === "GBP" || tar === "USD")) ||
      ((src === "EUR" || "GBP" || "USD") && tar === "SGD"))?
      rate = 0.3:
      (arr.indexOf(src)!=-1 && arr.indexOf(tar)!=-1) ?
      rate = 0.5 : 
     rate=0;
     
     console.log(res)

答案 1 :(得分:0)

您需要为每种条件添加tar ===

(tar === "EUR" || tar === "GBP" || tar === "USD")

或者,使用includes

(["EUR", "GBP", "USD"].includes(tar))

答案 2 :(得分:0)

如果条件匹配,您可以采用一个可以尽早返回值的函数

function check() {
    const group = ["EUR", "GBP", "USD"];
    if (src === "SGD" && tar === "AUD" || src === "AUD" && tar === "SGD") return 0.4;
    if (src === "SGD" && group.includes(tar) || group.includes(src) && tar === "SGD") return 0.3;
    if (arr.includes(src) && arr.includes(tar)) return 0.5;
    return 0;
}

简而言之

var rate = src === "SGD" && tar === "AUD" || src === "AUD" && tar === "SGD"
        ? 0.4
        : src === "SGD" && ["EUR", "GBP", "USD"].includes(tar) || ["EUR", "GBP", "USD"].includes(src) && tar === "SGD"
            ? 0.3
            : arr.includes(src) && arr.includes(tar)
                ? 0.5
                : 0;