【JavaScript变量】
Plus operator
An alternative method of retrieving a number from a string is with the +
operator.
- "1.1" + "1.1" = "1.11.1"
- (+"1.1") + (+"1.1") = 2.2 // Note: the parentheses are added for clarity, not required.
Declaring variables
You can declare a variable in two ways:
- With the keyword var. For example,
var x = 42
. This syntax can be used to declare both local and global variables. - By simply assigning it a value. For example,
x = 42
. This always declares a global variable and generates a strict JavaScript warning. You shouldn't use this variant.
Evaluating variables
A variable declared using the var
statement with no initial value specified has the value undefined
.
An attempt to access an undeclared variable will result in a ReferenceError
exception being thrown:
- var a;
- console.log("The value of a is " + a); // prints "The value of a is undefined"
- console.log("The value of b is " + b); // throws ReferenceError exception
You can use undefined
to determine whether a variable has a value. In the following code, the variable input
is not assigned a value, and the if
statement evaluates to true
.
- var input;
- if(input === undefined){
- doThis();
- } else {
- doThat();
- }
更多资料参考:https://developer.mozilla.org/en/JavaScript/Guide/Values%2C_Variables%2C_and_Literals