简体   繁体   中英

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

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM