JS对象键是否带引号? [英] JS object keys with or without quotes?
问题描述
可能重复:
引号和不引号?
Possible Duplicate:
What is the difference between object keys with quotes and without quotes?
有兴趣吗,用对引号或不对引号写对象键是正确的方法?那是
Is interest, what is right way, write object keys in quotes or not? that is
var obj = {
"name": "Jhon"
}
或
var obj = {
name: "Jhon"
}
例如,从php代码echo json_encode(array("a"=>"aaa","b"=>"bbb"));
中得出的结果是具有带引号的键的对象.
但是例如,请参见jquery animate,在文档中是没有引号的键(这也是JS对象格式,对吧?)
for example, from php code echo json_encode(array("a"=>"aaa","b"=>"bbb"));
result is object who has keys with quotes.
But for example see jquery animate, in documentation is keys without quotes, (This is also JS object format, right?)
$("#someElement").animate({
marginLeft: "200px"
},
{
duration: 1000
});
那么,什么是正确的方法呢?
So, what is more right way?
推荐答案
不要混淆JSON对象和Javascript对象文字. JSON对象基本上只是一个字符串,其语法要求使用正确的引号.但是对于javascript对象,其属性周围的引号不是必需的.但是在某些情况下,您必须使用它们,例如:
Don't confuse JSON object and Javascript object literal. JSON object is basicly just a string and its syntax requires to have proper quotes. However for javascript object quotes around its properties are not necessary. But in some cases you have to use them, e.g:
var test = {
"with spaces": 12
}
这篇关于JS对象键是否带引号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!