[removed] what's colon operator in variable na

2019-06-14 09:09发布

问题:

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.

  1. It's used to separate keys from values in the JSON notation.

    var db = { name: dbFunction(name) };

  2. It's the ternary operator:

    var db = (1 == 1 ? true : false);

  3. 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;
}