Should I use an empty property key?

前端 未结 5 758
名媛妹妹
名媛妹妹 2020-12-13 08:18

I\'ve tested this only in Firefox, but apparently you can use an empty string as a key to a property in an object. For example, see the first property here:

         


        
5条回答
  •  轮回少年
    2020-12-13 08:59

    An object's key must be a string, and the empty string ('') is a string. There is no cross browser issue that I've ever come across with empty strings, although there have been very few occasions where I thought it was acceptable to use an empty string as a key name.

    I would discourage the general usage of '' as a key, but for a simple lookup, it'll work just fine, and sounds reasonable. It's a good place to add a comment noting the exceptional circumstance.

    Additionally, during lookup you may have issues with values that are cast to a string:

    o = {...} //some object
    foo = 'bar';
    
    //some examples
    o[foo] //will return o['bar']
    o[null] //will return o['null']
    o[undefined] //will return o['undefined']
    

    If you'd like to have null and undefined use the '' key, you may need to use a fallback:

    key = key || '';
    

    If you might have non-string values passed in, it's important to cast too:

    key = key || '';
    key = '' + key;
    

    note that a value of 0 will turn into '', whereas a value of '0' will stay '0'.


    In most cases, I find I'm picking a pre-defined value out of a hashtable object. To check that the value exists on the object there are a number of options:

    //will be falsey if the value is falsey
    if (o[key]) {...}
    
    //will return true for properties on the object as well as in the prototype hierarchy
    if (key in o) {...}
    
    //returns true only for properties on the object instance
    if (o.hasOwnProperty(key)) {...}
    

提交回复
热议问题