最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript: what's colon operator in variable name? - Stack Overflow

programmeradmin2浏览0评论

i have code like this:

var db: name = dbFunction(true);

dbFunction returning Object.

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

i have code like this:

var db: name = dbFunction(true);

dbFunction returning Object.

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

Share Improve this question edited Nov 21, 2011 at 11:45 Matt 75.3k26 gold badges156 silver badges180 bronze badges asked Nov 21, 2011 at 11:38 Marcin KarkochaMarcin Karkocha 412 bronze badges 3
  • It is causing a syntax error to be thrown. – Quentin Commented Nov 21, 2011 at 11:41
  • 1 I have code created by IBM and i dont think it's syntax error – Marcin Karkocha Commented Nov 21, 2011 at 12:20
  • I've inherited some working code with something similar const store: Object = configureStore(), and am similarly confused. – mstringer Commented Feb 13, 2017 at 22:02
Add a ment  | 

3 Answers 3

Reset to default 5

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 mon).

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;

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.

It is also used in switch cases:

switch(product) {
    case "apple":
        return "Yum";
        break;
    case "orange":
        return "juicy!";
        break;
    case "milk":
        return "cold!";
        break;
}
发布评论

评论列表(0)

  1. 暂无评论