Javascript: what's colon operator in variable name?

最后都变了- 提交于 2019-12-23 06:00:15

问题


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)
};
  1. It's the ternary operator:

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

  1. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!