Resolve the difference between naming a variable when it is declared and naming it as an object attribute
- 2020-03-30 00:47:51
- OfStack
This title is a mouthful, and Javascript names variables according to the rules
1. The first character must be a letter, a Chinese character, an underscore (_) or a dollar sign ($).
The rest can be underscores, Chinese characters, dollar signs and any letters or Numbers
The following declared variables are correct
var p,$p,_p;
var long , wide ;
The following is false
var .p;//Only letters, Numbers, underscores, or dollar signs
var -p;//Only letters, Numbers, underscores, or dollar signs
var p*;//Only letters, Numbers, underscores, or dollar signs
var 4p,4 long ;//You can't start with a number
var long The degree of ;//You can't have Spaces in between
There are two ways to access it as an object property. One is the dot sign (.) operator and the other is the brackets ([]) operator.
var p = {name:"Jack"};
alert(p.name);// The dot
alert(p['name']);//brackets
1. The operator after the dot is required to be a legal identifier (that is, a legal variable name), which cannot be used for illegal ones
2, the brackets are required to be a string can be, do not have to be a legal variable name. For example, 4p is an illegal variable name (because it starts with a number), but can be used as an object property name (provided it is a string).
var p = {
"4p":"Jack",
"-3":"hello",
name:"Tom",
" I ":"me",
" I the ":"we"
};
alert(p.4p);//Illegal, syntax analysis error, can not start with a number
alert(p. I );//Legal, output "me"
alert(p. I the );//(there is a space between "I" and "we")
alert(p[" I the "]);//Legal, output "we", although there is a space between "I" and "we", can still use [] access
alert(p['4p']);//Legal, print "Jack"
alert(p.name);//Legal, print "Tom"
When we declare an object variable with a direct quantity, sometimes we put the attribute name in quotes, sometimes we don't, but whether we add it or not, the attribute type of the object is string
var book = {bname:"js Authoritative guide ","price":108};//Bname is not in quotes, price is
for(var attr in book) {
//Both outputs are strings, which means that js will dynamically convert them to string types
alert( attr + ":" + typeof(attr) );
}