I've taken on a new project,and there's a line of code that looks like this:
typeName() {
return {
1: 'leads',
2: 'cunstomer',
3: 'business'
}[this.optionValue]
},
it works well. I've never seen before. Then I tried in developer tools,but it don't work! Can anyone tell me why?
{1:'a'}[1]
Developer tools will report the error:Uncaught SyntaxError: Unexpected token ':'
Javascript expects an expression after the keyword return
. The dev tools console expects more or less what you would put in a file: a statement.
As stated in the comment by Jonas, statement are themselves expressions. And, given that certain syntax is used for both statements and expressions, whenever there is conflict, the statement takes precedence.
For example, the statement:
if (5 > 3) {
console.log(33);
}
is valid as console input, but not as a return value:
function myFunc() {
// return expects an expression
return if (5 > 3) {
console.log(33)
}
}
What you are essentially doing is putting a number inside a code block (a statement) with a colon afterwards and then trying to index that block.
// This makes no sense in the global scope
{
1:'a'
}[1]