[removed] what's colon operator in variable na

2019-06-14 09:05发布

i have code like this:

var db: name = dbFunction(true);

dbFunction returning Object.

I have question, what doing this colon operator in variable name?

3条回答
老娘就宠你
2楼-- · 2019-06-14 09:25

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.

查看更多
倾城 Initia
3楼-- · 2019-06-14 09:27

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;
查看更多
我命由我不由天
4楼-- · 2019-06-14 09:34

It is also used in switch cases:

switch(product) {
    case "apple":
        return "Yum";
        break;
    case "orange":
        return "juicy!";
        break;
    case "milk":
        return "cold!";
        break;
}
查看更多
登录 后发表回答