Home >Web Front-end >JS Tutorial >Introduction to creating objects using literals in JavaScript_javascript tips

Introduction to creating objects using literals in JavaScript_javascript tips

WBOY
WBOYOriginal
2016-05-16 16:23:151361browse

In JavaScript, you can use literals to directly create a new object:


Copy code The code is as follows:

var obj = {a:27, "b":99};


As mentioned above, when using literals to create objects, the property definition in the object can be enclosed in single or double quotes, or the quotes can be ignored. However, when special characters such as spaces and slashes appear in the property, or when the property used conflicts with JS keywords, quotation marks must be used.

When using literals to create objects, the property can be an empty string, and spaces can also appear in the property:


Copy code The code 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’s worth noting that JavaScript creates a completely new object every time a literal is used, even if the same literal is used:


Copy code The code 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 at the end ("," appears before the "}" character), some JavaScript interpreters will report an error. In fact, in IE7, this behavior will cause the browser to freeze and other problems. In the ECMAScript 5 standard, it is legal for "," to appear before the "}" character, and the comma will be ignored.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn