问题
i have code like this:
var db: name = dbFunction(true);
dbFunction returning Object.
I have question, what doing this colon operator in variable name?
回答1:
It's a high tech operator that guarantees a syntax error when used like that.
In it's normal use, you might see it used in object literal syntax to denote key:value pairs;
var object = {
"name": "value",
"name2": "value2"
}
It can also be used to define a label (less common).
loop1:
for (var i=0;i<10; i++) {
for (var j=0;j<10;j++) {
break loop1; // breaks out the outer loop
}
}
And it's part of the ternary operator;
var something = conditional ? valueIfTrue : valueIfFalse;
回答2:
The colon has several uses in JavaScript.
- It's used to separate keys from values in the JSON notation.
var db = {
name: dbFunction(name)
};
- It's the ternary operator:
var db = (1 == 1 ? true : false);
- Labels aka
GOTO
. Stay away from them.
回答3:
It is also used in switch cases:
switch(product) {
case "apple":
return "Yum";
break;
case "orange":
return "juicy!";
break;
case "milk":
return "cold!";
break;
}
来源:https://stackoverflow.com/questions/8211204/javascript-whats-colon-operator-in-variable-name