开发者

A question about JavaScript object property name

开发者 https://www.devze.com 2023-02-11 03:29 出处:网络
I\'ve a question about JavaScript object property name. Check out codes below: <!DOCTYPE html> <meta charset=\"UTF-8\">

I've a question about JavaScript object property name. Check out codes below:

<!DOCTYPE html>
<meta charset="UTF-8">
<title>An HTML5 document</title>
<script>
    var obj = {
        123: 'go' // 123 is not a valid JavaScript name. No error here.
    };
    var obj2 = {
        123a: 'go' // An Error occurred.
    };
</script>

If a JavaScript object's property name is a valid JavaScript identifier, obj开发者_运维知识库ect porperty name's quotes are not necessary.

E.g.

({go_go: 'go'}); // OK
({go-go: 'go'}); // Fail

In the codes above, 123a is an invalid JavaScript name and it's not be quoted. So An error occurred. But 123 is also an invalid JavaScript name and also it's not quoted, why no error here? Personally I think 123 must be quoted.

Thank you!


Have a look at the specification:

ObjectLiteral :
    { }
    { PropertyNameAndValueList }
    { PropertyNameAndValueList  ,}

PropertyNameAndValueList :
    PropertyAssignment
    PropertyNameAndValueList , PropertyAssignment

PropertyAssignment :
    PropertyName : AssignmentExpression
    get PropertyName ( ){ FunctionBody }
    set PropertyName ( PropertySetParameterList ){ FunctionBody }

PropertyName :  
    IdentifierName
    StringLiteral
    NumericLiteral

So a property name can be either an identifier name, a string or a number. 123 is a number whereas 123a is neither of those above.


The key portion of each key-value pair can be written as any valid JavaScript identifier, a string (wrapped in quotes) or a number:

var x = {
    validIdentifier: 123,
    'some string': 456,
    99999: 789
};

See the spec: http://bclary.com/2004/11/07/#a-11.1.5


123 is not, per-se, an invalid property name. Any property name that is not a string is typecast to a string with the toString method.

0

精彩评论

暂无评论...
验证码 换一张
取 消