【发布时间】:2020-01-12 11:03:35
【问题描述】:
我是 JavaScript 新手。请原谅,如果愚蠢的问题。
下面的 sn-p 是有道理的。没什么特别的:
const RED = 'red';
const ORANGE = 'orange';
const YELLOW = 'yellow';
const BLUE = 'blue';
const cat = 'blue';
function getThreatLevel(color){
switch(color){
case RED:
return 'severe';
case ORANGE:
return 'high';
case YELLOW:
return 'elevated';
case BLUE:
return 'low';
default:
console.log("I DON'T KNOW THAT COLOR!")
}
}
getThreatLevel(BLUE) = '低'
getThreatLevel(cat) = '低'
但是,将前 4 个变量的类型更改为符号时:
const RED = Symbol('red');
const ORANGE = Symbol('orange');
const YELLOW = Symbol('yellow');
const BLUE = Symbol('blue');
const cat = 'blue';
function getThreatLevel(color){
switch(color){
case RED:
return 'severe';
case ORANGE:
return 'high';
case YELLOW:
return 'elevated';
case BLUE:
return 'low';
default:
console.log("I DON'T KNOW THAT COLOR!")
}
}
getThreatLevel(BLUE) = '低'
getThreatLevel(cat) = '我不知道那种颜色!'
为什么cat 不再返回“低”?
【问题讨论】:
-
因为
string不是Symbol-> Symbols don't Auto-Convert to "strings" (MDN) -
@Andreas 谢谢
标签: javascript switch-statement symbols