This title is really hard to pronounce, the rules followed by Javascript naming variables
1. The first character must be a letter, Chinese character, underscore (_) or dollar sign ($)
2. The rest can be underscores, Chinese characters, dollar signs and any letters and numbers
The following declaration of variables is correct
var p, $p,_p;
var length, width;
The following is wrong
var .p;//It can only be letters, numbers, underscores or dollar signs
var -p;//It can only be letters, numbers, underscores or dollars Symbol
var p*;//can only be letters, numbers, underscores or dollar signs
var 4p, 4 long;//cannot start with a number
var length;//cannot have spaces in the middle
When used as an object attribute, there are two ways to access it. One is the dot (.) operator, and the other is the square bracket ([]) operator.
var p = {name:"Jack"};
alert(p.name);//The dot sign
alert(p['name']);//The square brackets
1. The dot sign requires subsequent operations Yuan is a legal identifier (that is, legal variable naming), and illegal ones cannot be used
2. The square brackets require a string, not a legal variable name. For example, 4p is an illegal variable name (because it starts with a number), but it can be used as an object attribute name (provided it is a string)
var p = {
"4p":"Jack",
"-3":"hello",
name :"Tom",
"我":"me",
"我们":"we"
};
alert(p.4p);//Illegal syntax An error is reported during analysis and cannot start with a number
alert(p.我);//Legal, output "me"
alert(p.we);//Illegal, an error is reported during syntax analysis ("I" and There is a space between "we")
alert(p["we"]);//Legal, output "we", although there is a space between "I" and "we", you can still use [] to save Take
alert(p['4p']); // legal, output "Jack"
alert(p.name); // legal, output "Tom"
Use When declaring an object variable directly, we sometimes add quotation marks to the attribute name, sometimes we do not. However, regardless of whether it is added or not, the attribute type of the object is string
var book = {bname:"js authoritative guide","price":108};//bname without quotation marks , price added
for(var attr in book) {
//Both outputs are strings, indicating that js will dynamically convert them into string types
alert( attr ":" typeof(attr ) );
}