JS Basics-Variables

Source: Internet
Author: User

A. Variable type
Variable type constructor function Example

Type detection typeof

String function String ()

var t = "Chua";

var m = new String ("Chua");

"String"

Digital function number ()

var t = 12;

var m = new Number (12);

"Number"

Boolean function Boolean ()

var t = false;

var m = new Boolean (0);

var m1 = new Boolean (false);

"Boolean"

Array function Array ()

var t = [n/a];

var m = new Array (+/-);

var m1 = new Array (3);

M1[0] = 1;

M1[1] = 2;

M1[2] = 3;

"Object"

Object function Object ()

var t = {name: "Chua"};

var m = new Object ({name: "Chua"});

var m1 = new Object ();

M1.name = "Chua";

"Object"

Null

None, indicating that there should be no value (invalid value)

, NULL is considered a placeholder for the object

var t = null; Note lowercase

function m (name) {

if (name = = NULL) {alert (name)}

}

m (null); Null

"Object"

Undefined

None, indicating the variable uninitialized value

Or the arguments in the function are not passed

var t = undefined;//lowercase

var tUn;

alert (tUn);//undefined

function m (name) {

if (name = = undefined) {

Alert ("No parameters passed")

}

}

m ();//"No parameters passed"

"Undefined"

function (this is considered a

Compare special types of variables)

function function ()

var t = function () {}; A function named T is constructed.

var m = new function ();/*t points to an anonymous function,

function cannot be constructed for functions with entities at present

This shows that T and M are two different things, not equivalent */

How anonymous functions are written

(function () {}); The no parentheses operator will report a syntax error

A small application

(function () {alert (1)}) (); 1, build anonymous functions and execute immediately

(function (name) {alert (name)}) ("Chua");

"Chua", building an anonymous function and executing it immediately

"Function"

Date type function Date ()

var t = new Date ();//Get current time

var m = new Date ("January 1,2000 22:00:00");

Set a time

The following remarks will detail the compatibility of date initialization

"Object"
Regular type

function RegExp (pattern,

attributes )

var t =/\d+/;//matches one or more digits

var m = new RegExp ("\\d+");

More Regular Expression Content reference

http://blog.csdn.net/zaifendou/article/details/5746988

Http://www.w3school.com.cn/jsref/jsref_obj_regexp.asp

"Object"
Error type function Error ()

var t = new error ("syntax error");

alert (t.message); "Syntax error"

"Object"

Note: non-Generalized object types (functions, arrays are generalized object types) The variable constructed by the constructor is a special object that is simply converted to a non-generalized object type when compared to other non-generalized object types. So

New // true New // false

Date Initialization:

In general, there are three ways to initialize dates that are supported by all browsers:

  1. Create a Date object with a string:

New Date ("Month dd,yyyy hh:mm:ss");
New Date ("Month dd,yyyy");
  2. Multiple numeric parameter creation date objects:
New Date (YYYY,MTH,DD,HH,MM,SS);//Where MTD value is 0-11
New Date (YYYY,MTH,DD);

  3. Create a date using milliseconds
The new Date (MS), or//parameter represents the number of milliseconds between the time to create and the GMT time of January 1, 1970

The meanings of the various functions are as follows:
Month: The name of the months in English, from January to December

MTH: The month is expressed in integers, from 0 (January) to 11 (December)

DD: Represents the day ordinal of one months, from 1 to 31

YYYY: four-digit year

HH: Hours, from 0 (midnight) to 23 (11 o'clock in the evening)

MM: Number of minutes, integers from 0 to 59

SS: Number of seconds, integers from 0 to 59

MS: Number of milliseconds, integer greater than or equal to 0

For those single digits, writing 0x or x can

Such as:

New Date ("January 1,2001 12:00:00");

New Date ("January 1,2001");

New Date (2000,0,1,12,0,0);

New Date (2000,0,1);

New Date (978321600000);

The various forms of creation above represent the day of January 1, 2000.

An undeclared variable uses an operator other than typeof, which causes an error because the other operators can only be used on declared variables.

The detection type in the table shows that typeof is only a generalized type. if you want to detect the true type of a variable, you can refer to the jquery approach

varCore_tostring ={}.tostring;core_tostring.call ([]);//"[Object Array]"Core_tostring.call ({});//"[Object Object]"Core_tostring.call (function(){});//"[Object Function]"Core_tostring.call (1);//"[Object number]"Core_tostring.call ("");//"[Object String]"Core_tostring.call (NewDate ());//"[Object Date]"Core_tostring.call (/\d+/);//"[Object RegExp]"Core_tostring.call (NewError ());//"[Object Error]"

B. Original Type

original value and reference value

in ECMAScript, a variable can hold two types of values, that is, the original value and the reference value.

The original value (primitive value) is a simple data field stored in the stack (stack), that is, their values are stored directly in the location of the variable access . The reference value (reference value) is the object stored in the heap (heap), that is, the value stored in the variable is a pointer (point) to the memory of the storage object.

ECMAScript has 5 primitive types (primitive type), namely Undefined, Null, Boolean, number, and String

There are some key points to be aware of in these 5 types

Undefined

Undefined has several meanings: variable definitions (declarations) but no assignment, missing arguments in function calls are considered undefined, and values returned when the function has no explicit return value undefined

It is important to note that the value undefined differs from the value that is not defined (declared) . However, the typeof operator does not really differentiate between these two values

var Un;alert (typeof//"undefined"alert (typeof//"undefined ", the variable demo is not defined

undefined variables can only use the TypeOf operator, and other operators must be used for defined variables

// error, because Demo2 is undefined

Null:

Null is used to represent an object that does not already exist (this is briefly described when discussing the typeof operator). If the function or method is to return an object, the object returned is usually null when it is not found.

Why the TypeOf operator returns "Object" for null values. This is actually a legacy of JavaScript history. Now NULL is considered a placeholder for the object, explaining the contradiction, but technically it is still the original value .

  The value undefined is actually derived from the value null, so ECMAScript defines them as equal

Alert (null = = undefined);  // "true"

Boolean type:

False is not equal to 0, 0 can also be converted to false,true and 1 if necessary. It is safe to use both in a Boolean statement.

Alert (false//truealert (true//truealert (true )  falsealert (false//false )

Number type:

  The first digit of the octal literal must be 0, and the subsequent number can be any octal digit (0-7);

16 binary literals, the first number must be 0, followed by the letter x, followed by any hexadecimal digits (0 to 9 and A to F). The letters can be in uppercase or lowercase .

// 7 // 9 //  the //  the //  the

Although all integers can be represented as octal or hexadecimal literals, all mathematical operations return a decimal result

  To define a floating-point value, you must include a decimal point and a number after the decimal point (for example, 1.0 instead of 1)

  Using scientific notation to represent floating-point numbers, you can represent a number as a number (including a decimal number) plus E (or e), followed by a multiple of 10.

// 122000 // 0.0000122

ECMAScript By default converts a floating-point number with 6 or more 6 leading 0 to scientific notation.

Several special values are also defined as number types:

1. Number.MAX_VALUE and Number.min_value, which define the outer bounds of the set of number values. All ECMAScript numbers must be between these two values. However, the resulting numeric result can be calculated without falling between the two values.

2. Infinity Number.POSITIVE_INFINITY and Infinity small number.negative_infinity. Both means the value is no longer a number.

Use Isfinite () to determine if the value is finite.

// false // false // true // true

3.NaN, which represents a non-number (not a digit). NaN is a strange special value. In general, this occurs when a type (String, Boolean, etc.) conversion fails. For example, the string "Chua" is converted to a numeric value and fails because there is no value equivalent to it. As with infinity, NaN cannot be used for arithmetic calculations. another peculiarity of NaN is that it is not equal to itself :

Nan = = nan;  // false

For this reason, it is not recommended to use the NaN value itself. Use function isNaN to determine whether a non-numeric value

Alert (IsNaN ("Chua"));  // "true"alert (IsNaN ("666"));  // "false"

String:

The string type is the only original type that does not have a fixed size.

C. Variable declaration (the function type is also considered a variable here)

The variable declaration in JS is explicitly declared and implicitly declared .

  the display declaration refers to the use of a declaration that begins with VAR (except for function declarations).

var // declares a variable to be T function // declares a function named M

  An implicit declaration is a variable that is explicitly declared without using Var .

  It is important to note that an implicit declaration does not declare a variable in the declaration before the execution of the code, but does not find the variable when it executes to the code snippet, and then creates a variable under that scope , so if the variable is used before the variable expression, it will report an error that the variable is undefined.

//error, b not defined // Declare the variable B and assign a value of 1 to B // 1

So an implicit declaration is a convenience for that language, but it's also dangerous if you can't keep track of variables closely. The best habit is to always declare all variables, just as you would with other programming languages.

Characteristics of declaring variables

1. No explicit type declaration is required

2. Variables defined with the same VAR statement do not have to have the same type

var name= "Chua", age=20;

3. Not necessarily initialized (they are initialized behind the scenes)

var name;

4. Can store different types of values

var name = "chua;name = one; "

When using variables, a good coding habit is to always store values of the same type.

Variable naming

    • The first character must be a letter, an underscore (_), or a dollar sign ($)
    • The remaining characters can be underscores, dollar signs, or any alphabetic or numeric characters

D. Variable declarations before all code is executed

Let's look at an example.

var inch window; alert (In_window);  //true if inch window)) {  var a = 1;}

Alert (In_window) shows true, and it's amazing that it's not.

If var a = 1 is removed, then alert (In_window) is displayed as false.

Let's take a look at the title again: variable declarations before all code executes.

Parsing: After the script is loaded, the browser scans the entire script, declaring all the variables in the display declaration (including the declaration in the expression) under all windows before executing the expression .

The above example declares that the variable A is declared in an expression, although the expression has not yet been executed, but the declaration has been declared in advance. of course, this declaration expression cannot be in a function . As follows

var inch Window;alert (In_window); // false function B () {  var a = 1;}

An implicit declaration is not declared in advance, and the preceding variable declaration has been parsed.

That was the declaration of the normal variable, what if it is a function declaration?

var inch Window;alert (In_window); //ie/chrome Display True,firefox Display False if inch window)) {  function  A () {}}

  Unfortunately, Ie/chrome scans the function declarations in expressions in the global scope and declares them in advance, but Firefox does not.

So this is inconclusive. Firefox will make the function declaration in the judgment statement as a function expression (the whole if judgment as an expression), the execution of the sentence to declare the function;Chrome will declare it in advance. All function declarations (including similar var m = function () {...} This is obviously a function of the function expression).

  

However, it is certain that function declarations and assignments are done at the same time during the declaration, and the variable assignment statements are executed as expressions .

var a = ' 1 '; function //1

The parsing step is to declare a variable A, then an invalid declaration (the declaration is in advance, the same declaration will only once), give a assignment to a function (the function declaration is assigned in the declaration process), the declaration completes after the execution code expression A = 1. So the result is 1.

  

function A () {}; var //function A () {}

The parsing step is to declare a variable, then assign a function to a, then no then (the declaration is advanced, the same declaration will only once).

    

var function return true  }; var
function () {return true};

The parsing step is to declare a variable to be a, then an invalid declaration (the function declaration is assigned in the declaration process), the declaration is completed after the execution of an expression to a function, then no then (the declaration is advanced).

  

There are several important concepts involved:

1 variable declarations are completed before they enter the execution expression.

2 function declarations are also in advance, and all function declarations have been declared before executing the code, as are declaration of variables

3 function declarations assign values to declared variables as functions in the process of declaration

  However, we do not advocate the use of this variable before the code that declares the variable, which is not intuitive and poorly maintained.

  If you feel this article is good, please click on the bottom right "recommended"!

JS Basics-Variables

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.