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

Detailed explanation of JS attribute names with quotes and without quotes

小云云
Release: 2018-02-22 09:15:33
Original
1595 people have browsed it

Generally, the attribute name can be quoted or not, and the effect is the same. This article mainly introduces to you the problems and solutions of adding quotes or not adding quotes to attribute names when declaring objects in JS. Friends in need can refer to it. I hope it can help everyone.


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 you can access them using . and [];

If the attribute name is a number, it must be surrounded by "" , and accessed using [] square brackets.

Related recommendations:

The difference between the Key in php array index with quotes and without quotes

The above is the detailed content of Detailed explanation of JS attribute names with quotes and without quotes. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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!