Understanding Javascript object initialization keys
Is there any difference between the following?:
var object1开发者_如何转开发= {
a: 0,
b: 1,
c: 2
};
vs
var object2= {
'a': 0,
'b': 1,
'c': 2
};
There's no difference in your example. There would be a difference if you wanted your property names to be a number or have spaces (both of which are valid, but strange).
var object3 = {
'123': 0,
'hello world' : 1
}
// This is valid
alert(object3['123']); // -> 0
alert(object3['hello world']); // -> 1
// This is not
alert(object3.123); // -> Syntax Error
If you have two minutes you might find this page VERY helpful.
http://bonsaiden.github.com/JavaScript-Garden/#object.general
The answer by jessegavin already explains everything that you asked about, but let me add one thing that you didn't asked about but might need to know in the future.
All of these are valid JavaScript object literals:
{ a: 0, b: 1, c: 2 }
{ 'a': 0, 'b': 1, 'c': 2 }
{ "a": 0, "b": 1, "c": 2 }
but only the last one is valid JSON. Not properly quoting the keys in JSON is probably the main reason of programs producing invalid JSON, and invalid JSON seems to be the main source of problems that people have with AJAX.
Not exactly the answer to your question but still it is relevant and may save you some trouble in the future.
No difference. Both syntax are correct
Both of those are equal because in javascript, object attrs. can either be strings or plain text.
精彩评论