What is the type of “keys” in JavaScript?

前端 未结 5 432
梦毁少年i
梦毁少年i 2020-12-05 17:52

I bumbed into one of those moments when I just lose the focus and start wondering on a silly question:

var a = {
  b: \"value\"
}

What is t

5条回答
  •  甜味超标
    2020-12-05 18:35

    Property names are automatically coerced into a string. You can try this yourself by using a numeric literal as a property name.

    var object = {
      .12e3: 'wut'
    };
    object[.12e3]; // 'wut'
    object['.12e3']; // undefined
    object['120']; // 'wut'
    
    // Let’s try another numeric literal:
    object = {
      12e34: 'heh'
    };
    object[12e34]; // 'heh'
    object['12e34']; // undefined
    object[1.2e35]; // 'heh'
    object['1.2e35']; // undefined
    object[1.2e+35]; // 'heh'
    object['1.2e+35']; // 'heh'
    

    For this reason, I’d recommend using only string literals for property names.

    From Unquoted property names / object keys in JavaScript, my write-up on the subject:

    Quotes can only be omitted if the property name is a numeric literal or a valid identifier name.

    […]

    Bracket notation can safely be used for all property names.

    […]

    Dot notation can only be used when the property name is a valid identifier name.

    I also made a tool that will tell you if any given property name can be used without quotes and/or with dot notation. Try it at mothereff.in/js-properties.

提交回复
热议问题