Home  >  Article  >  Web Front-end  >  The problem of adding quotes or not adding quotes to attribute names in JS

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

亚连
亚连Original
2018-06-05 17:34:081647browse

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);

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);

An error is reported at this time.

var obj = { 
  “333”: &#39;这个也会报错&#39; 
}; 
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": &#39;这个正确&#39;
};
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

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!

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