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 remaining characters can be underscores, Chinese characters, dollar signs and any letters and numbers.
The following variable declaration is correct
Copy the code code as follows:
var p,$p,_p;
var length, width;
The following is wrong
Copy the code code as follows:
var .p;//can only be letters, numbers, underscores or dollar signs
var -p;//can only be letters, numbers, underscores or dollar signs
var p*;//can only be letters, numbers, underscores or dollar signs
var 4p, 4 long; //cannot start with a number
var length; //There can be no spaces in the middle
As an object attribute, there are two ways to access it. One is the dot (.) operator, and the other is the square bracket ([]) operator.
Copy the code code as follows:
var p = {name:"Jack"};
alert(p.name);//dot sign
alert(p['name']);//square brackets
1. The dot requires that the operand behind it is a legal identifier (that is, a legal variable naming), and illegal ones cannot be used.
2. The 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)
Copy the code code as follows:
var p = {
"4p":"Jack",
"-3":"hello",
name:"Tom",
"我":"me",
"we":"we"
};
alert(p.4p);//Illegal, syntax analysis will report an error, cannot start with a number
alert(p.me);//Legal, output "me"
alert(p.we);//Illegal, syntax analysis will report an error (there is a space between "I" and "we")
alert(p["we"]);//Legal, output "we", although there is a space between "I" and "we", you can still use [] to access
alert(p['4p']);//Legal, output "Jack"
alert(p.name);//Legal, output "Tom"
When declaring an object variable using a direct variable, sometimes we add quotation marks to the attribute name, sometimes we do not add it, but regardless of whether it is added or not, the attribute type of the object is string.
Copy the code code as follows:
var book = {bname:"js authoritative guide","price":108};//bname is not quoted, price is added
for(var attr in book) {
//Both outputs are strings, indicating that js will dynamically convert them into string types.
alert( attr + ":" + typeof(attr) );
}