What characters are valid for JavaScript variable names?

后端 未结 12 1890
情深已故
情深已故 2020-11-21 04:26

Which characters can be used for naming a JavaScript variable?

I want to create a small \"extension library\" for my non-JavaScript users here at work (who all seem

12条回答
  •  天命终不由人
    2020-11-21 04:50

    From the ECMAScript specification in section 7.6 Identifier Names and Identifiers, a valid identifier is defined as:

    Identifier :: 
        IdentifierName but not ReservedWord
    
    IdentifierName :: 
        IdentifierStart 
        IdentifierName IdentifierPart 
    
    IdentifierStart :: 
        UnicodeLetter 
        $ 
        _ 
        \ UnicodeEscapeSequence 
    
    IdentifierPart :: 
        IdentifierStart 
        UnicodeCombiningMark 
        UnicodeDigit 
        UnicodeConnectorPunctuation 
        \ UnicodeEscapeSequence 
    
    UnicodeLetter 
        any character in the Unicode categories “Uppercase letter (Lu)”, “Lowercase letter (Ll)”, “Titlecase letter (Lt)”, 
        “Modifier letter (Lm)”, “Other letter (Lo)”, or “Letter number (Nl)”. 
    
    UnicodeCombiningMark 
        any character in the Unicode categories “Non-spacing mark (Mn)” or “Combining spacing mark (Mc)” 
    
    UnicodeDigit 
        any character in the Unicode category “Decimal number (Nd)” 
    
    UnicodeConnectorPunctuation 
        any character in the Unicode category “Connector punctuation (Pc)” 
    
    UnicodeEscapeSequence 
        see 7.8.4. 
    
    HexDigit :: one of 
        0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F
    

    which creates a lot of opportunities for naming variables and also in golfing. Let's try some examples.

    A valid identifier could start with either a UnicodeLetter, $, _, or \ UnicodeEscapeSequence. A unicode letter is any character from these categories (see all categories):

    • Uppercase letter (Lu)
    • Lowercase letter (Ll)
    • Titlecase letter (Lt)
    • Modifier letter (Lm)
    • Other letter (Lo)
    • Letter number (Nl)

    This alone accounts for some crazy possibilities - working examples. If it doesn't work in all browsers, then call it a bug, cause it should.

    var ᾩ = "something";
    var ĦĔĽĻŎ = "hello";
    var 〱〱〱〱 = "less than? wtf";
    var जावास्क्रिप्ट = "javascript"; // ok that's JavaScript in hindi
    var KingGeorgeⅦ = "Roman numerals, awesome!";
    

提交回复
热议问题