I've been tinkering with objects and seemingly you can have '' (an empty string) as a property name, like so:

o = {
    '':    'hello',
    1:     'world',
    'abc': ':-)',
};
console.log(o['']);

似乎工作得很好,但我很好奇地想知道,is this really valid?我戳了戳ECMA规范,问了我们知识渊博的朋友谷歌这个问题的变体,我的结论是I don't know.

My sources

http://www.jibbering.com/faq/faq_notes/square_brackets.html

推荐答案

Yes, technically its totally valid and you can safely use it. An object key needs to be a "string", which does not exclude an empty string.

If that is convenient or even useful is another story.

Should I use an empty property key?


Since the 'empty string' is one of the falsy values in ecmascript, consider the following example:

var foo = {
    ':-)': 'face',
    'answer': 42,
    '': 'empty'
};

Object.keys( foo ).forEach(function( key ) {
    if( key ) {
        console.log(key);
    }
});

That snippet would only log :-) and answer. So that is one pitfall for doing this.

Json相关问答推荐

Elasticsearch Go客户端错误:无效的SON格式:在中间件中索引文档时出错

如何使用JQ有条件 Select 值

删除JSON文件的特定内容

如何使用JQ将JSON字符串替换为解析后的类似功能?

如何实现一个通用的 serde_json::from_str

在 postgresql 中将行转换为 json 对象

如何将动态复杂 json 解析为dart 对象或模型

PowerShell - 如何迭代 PSCustomObject 嵌套对象?

哪个更好:Json 或 XML (PHP)

Python Flask-Restful POST 不采用 JSON 参数

使用 simplejson 序列化简单类对象的最简单方法?

验证和格式化 JSON 文件

Json.Net:用于自定义命名的 JsonSerializer-Attribute

字符串的 Gson 数组到 JsonArray

jQuery fullcalendar 发送自定义参数并使用 JSON 刷新日历

Golang struct 的 XML 和 JSON 标签?

如何使用 SwiftyJSON 将字符串转换为 JSON

将序列化表单的数据转换为 json 对象

Python 到 JSON 序列化在十进制上失败

通过 JSON 发送 64 位值的公认方式是什么?