cha*_*rit 6 javascript dictionary coding-style
在大多数JSON序列化器/反序列化器中,javascript字典/散列数组中的"关键"部分被写为字符串.
使用字符串作为键而不是只键入目标名称有什么好处?
例如,假设我定义了两个对象k1
,k2
如下所示:
var k1 = { a: 1, b: 2, c: 3 }; // define name normally
var k2 = { "a": 1, "b": 2, "c": 3 }; // define name with a string
Run Code Online (Sandbox Code Playgroud)
然后我运行了以下测试:
alert(k1 == k2); // false (of course)
alert(k1.a == k2.a); // true
alert(k1["b"] == k2["b"]); // true
alert(uneval(k1)); // returns the k1 object literal notation.
alert(uneval(k2)); // returns the same string as above line.
alert(uneval(k1) == uneval(k2)); // true
Run Code Online (Sandbox Code Playgroud)
那么关键是用双引号(一个字符串)来k2
定义的方式是什么,而不是仅仅按照定义的方式键入键名k1
?
我刚刚在Ajaxian看到这一点指向Aaron Boodman的博客文章:
chromium.tabs.createTab({
"url": "http://www.google.com/",
"selected": true,
"tabIndex": 3
});
Run Code Online (Sandbox Code Playgroud)
由于他也使用tabldex的camel case,我根本没有看到使用字符串的任何意义.
为什么不:
chromium.tabs.createTab({
url: "http://www.google.com/",
selected: true,
tabIndex: 3
});
Run Code Online (Sandbox Code Playgroud)
为什么会JS忍者如下转弯的惯例url
,selected
并tabIndex
为一个字符串?