Home > Web Front-end > JS Tutorial > body text

The problem of adding quotes or not adding quotes to attribute names in JS

亚连
Release: 2018-06-05 17:34:08
Original
1654 people have browsed it

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[&#39;name&#39;] + &#39;<br />&#39; ); 
document.write( obj.age);
Copy after login

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 : &#39;这个会报错&#39; 
}; 
document.write( obj.333);
Copy after login

An error is reported at this time.

var obj = { 
  “333”: &#39;这个也会报错&#39; 
}; 
document.write( obj.333);
Copy after login

If the attribute name is a number, it must have double quotes and be accessed with [] square brackets.

var obj = {
  "333": &#39;这个正确&#39;
};
console.log(obj["333"]);
Copy after login

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

Use vuex to store and store login status Browsing is not allowed when you are not logged in. What are the specific methods?

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!

Related labels:
js
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!