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

Using colons in javascript variable names (eg. a:b:c) - Stack Overflow

programmeradmin1浏览0评论

I have just noticed that I can do the following in javascript...

a:b:c:d = "happy days";
a:b:c = function(text){alert(text);};

I cannot however do...

var a:b:c:d = "happy days"; 
// or
var myObj = {prop:a:b:c:d};

I was not expecting this syntax to work under any circumstances. Does anyone have any idea what is going on when I successfully use the 'a:b=x' notation?

I have just noticed that I can do the following in javascript...

a:b:c:d = "happy days";
a:b:c = function(text){alert(text);};

I cannot however do...

var a:b:c:d = "happy days"; 
// or
var myObj = {prop:a:b:c:d};

I was not expecting this syntax to work under any circumstances. Does anyone have any idea what is going on when I successfully use the 'a:b=x' notation?

Share Improve this question asked Jan 9, 2012 at 0:57 JonathonJonathon 1651 silver badge11 bronze badges 5
  • That's peculiar, that is. You can even read the value back again, which I really didn't expect. – Joe White Commented Jan 9, 2012 at 1:01
  • 1 a:b:c:d = "happy days"; assigns 'happy days' to d. not to a:b:c:d.. – Gabriele Petrioli Commented Jan 9, 2012 at 1:02
  • After you initialize a:b:c:d, type a:bbbb:cccccc:garble:d – itdoesntwork Commented Jan 9, 2012 at 1:02
  • 2 Side note: this is perfectly legal: window["a:b:c:d"] = "happy days"; – Wayne Commented Jan 9, 2012 at 1:07
  • @lwburk - Thanks for this. Your comment was the nudge I needed to get find the solution to the problem which raised this question. See below. – Jonathon Commented Jan 13, 2012 at 0:57
Add a comment  | 

2 Answers 2

Reset to default 17

A colon in ECMAscript is there for three reasons

  • separating object keys from its values
  • inline conditional statements
  • labeling

you discoverd the latter. What you are basically doing is creating a label called a, then b, then c and finally you are assigning a value to a global variable d. So after

a:b:c:d = "happy days";

console.log(a); // reference error
console.log(d); // "happy days";

Most common usage for this is within a switch statement where we do it like

switch( foo ) {
    case 0: break;
    case 1: break;
    // etc
}

But you can also directly "target" a label with the continue statement. That comes very close to goto in many other languages and looks like

foobar:
for(var i = 0; i < 10; i++) {
    for(var j = 0; j < 10; j++) {
        if( j === 2 )
            continue foobar;
    }
}

Quoting the ECMAScript standard: “A Statement may be prefixed by a label. Labelled statements are only used in conjunction with labelled break and continue statements.” A label consists of an identifier and a colon. So a:b:c:d = "happy days"; is just an assignment statement d = "happy days"; prefixed by three labels, which have no effect as such.

发布评论

评论列表(0)

  1. 暂无评论