Home > Article > Web Front-end > The problem of adding quotes or not adding quotes to attribute names in JS
This article mainly introduces the problems and solutions of adding quotes and not adding quotes to attribute names when declaring objects in JS. Friends in need can refer to the following
In general, attribute names should be quoted or not. Either way, the effect is the same.
var obj = { name : '你好', 'age' : 1, }; document.write( obj['name'] + '<br />' ); document.write( obj.age);
Both the above two lines of code can be executed correctly.
If and only if your attribute name is an illegal and weird name, an error will be reported.
var obj = { 333 : '这个会报错' }; document.write( obj.333);
An error is reported at this time.
var obj = { “333”: '这个也会报错' }; document.write( obj.333);
If the attribute name is a number, it must have double quotes and be accessed with [] square brackets.
var obj = { "333": '这个正确' }; console.log(obj["333"]);
Conclusion: Use legal attribute names and use . and [] to access them;
If the attribute name is a number, it must be surrounded by "" and accessed with [] square brackets.
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
Solve the problem that lower version browsers do not support the import of es6
Detailed explanation of the four ways of binding this event in react
The above is the detailed content of The problem of adding quotes or not adding quotes to attribute names in JS. For more information, please follow other related articles on the PHP Chinese website!