JavaScript变量

JavaScript变量

Plus operator

An alternative method of retrieving a number from a string is with the + operator. 

  1. "1.1" + "1.1" = "1.11.1"  
  2. (+"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:

  1. var a;  
  2. console.log("The value of a is " + a); // prints "The value of a is undefined"  
  3. 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.

  1. var input;  
  2. if(input === undefined){  
  3.   doThis();  
  4. else {  
  5.   doThat();  
  6. }  

更多资料参考:https://developer.mozilla.org/en/JavaScript/Guide/Values%2C_Variables%2C_and_Literals

原文地址:https://www.cnblogs.com/tekkaman/p/2565522.html