In JavaScript, you can use literals to directly create a new object:
The code copy is as follows:
var obj = {a:27, "b":99};
As mentioned above, when creating an object with literals, the property definition in the object can be included in single or double quotes, or quotation marks can be ignored. However, when special characters such as spaces and slashes appear in the property, or when the property used conflicts with the JS keyword, quotes must be used.
When creating objects with literals, property can be an empty string, and spaces can also appear in property:
The code copy is as follows:
//empty string is allowed as object property
var o = {"":88, "p":99};
console.log(o);//Object { =88, p=99}
//spaces can be included in property
var o2 = {"good score":99, "bad score":52};
console.log(o2);//Object {good score=99, bad score=52}
It is worth noting that even though the literals are used, JavaScript creates a completely new object every time you use the literals:
The code copy is as follows:
//every object literal creates a new and distinct object.
var x = {a:18, b:28};
var y = {a:18, b:28};
console.log(x === y);//false
In a literal, if there is an extra comma ("}" character before ","), then some JavaScript interpreters will report an error. In fact, in IE7, this behavior will lead to problems such as browser fake death. In the ECMAScript 5 standard, "}" character appears before "," is legal, and the comma will be ignored directly.