我来自Ruby世界,后来进入JavaScript世界。 Ruby语言的一项功能是case
语句,用于评估目标值:
my_val = case my_var
when "var1" then "value1"
when "var2" then "value2"
else "value3"
end
# my_val evaluated to a specific value
puts my_val
我可以像上面的JavaScript一样简洁吗?这是我得到的最接近的东西:
let myVal = null;
switch (myVar) {
case "var1":
myVal = "value1";
break;
case "var2":
myVal = "value2";
break;
default:
myVal = "value3";
}
// my_val evaluated to a specific value
console.log(myVal);
答案 0 :(得分:3)
您可以使用具有三进制的对象来设置默认值,如下所示:
const obj = {
"var1":"value1",
"var2":"value2",
"defaultVal": "value3" // default value
},
getVal = sVar => sVar in obj ? obj[sVar] : obj["defaultVal"];
// Use case 1:
console.log(getVal("var1")); // get "var1" from the object
// Use case 2:
console.log(getVal("foo")); // get "foo" from the object, doesn't exsist, so we get the fault value
上面创建了一个对象,该对象中的每个键都指向一个值(即myVar
应该变成什么)。如果myVar
不在对象中,它将默认为defaultVal
;如果它不在对象中,它将检索关联的值。
答案 1 :(得分:2)
或者,如果仅返回值,则可以使用Map。
let map = new Map([["var1","value1"], ["var2", "value2"]])
const getVar = myVar => map.has(myVar) ? map.get(myVar) : "value3"
// Use
let myVar = 'var2'
myVar = getVar(myVar)
console.log(myVar)
答案 2 :(得分:1)
您的代码有效:
let myVal = null;
let myVar = 'var1';
switch (myVar) {
case "var1":
myVal = "value1";
break;
case "var2":
myVal = "value2";
break;
default:
myVal = "value3";
}
// my_val evaluated to a specific value
console.log(myVal);
但是没有switch
语句的一种更好的方法:
const obj = {
var1: 'value1',
var2: 'value2',
default: 'value3'
};
const myVar = 'var1';
const myVal1 = obj[myVar] || obj.default;
const myVal2 = obj['asdfasdf'] || obj.default;
console.log(myVal1);
console.log(myVal2);
答案 3 :(得分:1)
您可以使用&&
中的Boolean Operators ||
和Javascript
来达到类似的目的:
let my_var = "var2";
let my_val =
(my_var === "var1" && "value1") ||
(my_var === "var2" && "value2") ||
"value3";
console.log(my_val);
let my_var2 = "var3";
let my_val2 =
(my_var2 === "var1" && "value1") ||
(my_var2 === "var2" && "value2") ||
"value3";
console.log(my_val2)
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
侧面说明:此方法仅适用于原始Javascript
值。让我们看一些方法失败的例子:
let my_var = [1,2,3];
let my_val =
(my_var === "var1" && "value1") ||
(my_var === [1,2,3] && "value2") ||
"value3";
console.log(my_val);
let my_var1 = {"a":"b"};
let my_val1 =
(my_var1 === "var1" && "value1") ||
(my_var1 === {"a":"b"} && "value2") ||
"value3";
console.log(my_val1);
let my_var2 = NaN;
let my_val2 =
(my_var2 === "var1" && "value1") ||
(my_var2 === NaN && "value2") ||
"value3";
console.log(my_val2);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}