JavaScript Data types

Source: Internet
Author: User
Tags object object string to number

One, data type

The following is based on ES5 (ES6 introduces a new primitive data type, symbol, which represents a unique value. It is the seventh data type of the JavaScript language. )

JavaScript is a weakly typed dynamic language, and it is seemingly simple to define variables without specifying a type, but there are cumbersome conversion logic behind it. Let's take a look at the common data types of JS and the implicit conversion logic behind it.

There are 5 simple data types (also called basic data Types) in ES5: number,string,boolean,null,undefined (null and undefined are two special basic data types, as described below); and a complex data type Object (function is a special kind of object, which is discussed later)

Undefined type:

The undefined type has only one value, that is, a special undefined. When you declare a variable using var but do not initialize it, the value of the variable is undefined, for example:

var= = undefined); // true

This example declares only the variable message, but does not initialize it. Comparing this variable with the undefined literal, the result shows that they are equal. This example is equivalent to the following example:

var= = undefined); // true  

This example initializes the variable message with the undefined value display. But we do not need to do this because the uninitialized value gets the undefined value by default.

(Generally, there is no case where a variable needs to be set to a undefined value.) The main purpose of the literal value undefined is to compare, and this value is not specified in versions prior to ECMA-262 version 3rd. the 3rd edition introduces this value to formally differentiate between null object pointers and uninitialized variables . )

However, the variables that contain undefined values are not the same as those that have not been defined. Take a look at the following example:

var message; // the undefined value is obtained by default after this variable declaration // The following variable does not declare // varage alert (message); // ' undefined 'alert (age); // Error  generated Uncaught referenceerror:age is not defined (...)

Running the above code, the first warning box displays the value of the variable message, which is ' undefined '. The second warning box causes an error because it is passed to the alert () function, which is a variable that has not yet been declared. For variables that have not been declared, you can only perform one operation, which is to use the TypeOf operator to detect its data type.

However, it is confusing that executing the typeof operator on an uninitialized variable returns the undefined value, and the TypeOf operator that executes the undeclared variable also returns the undefined value. Take a look at the following example:

var message; // the undefined value is obtained by default after this variable declaration // The following variable does not declare // varage alert (typeof message); // ' undefined 'alert (typeof age); // ' undefined '

The result shows that the typeof operator, which executes the uninitialized and undeclared variables, returns the undefined value, which is logically justified, because although the two variables are fundamentally different from the technical point of view, it is virtually impossible to perform real operations on any of the variables.

(even if the uninitialized variable is automatically assigned the undefined value, we still recommend that the reader develop an explicit initialization variable-the habit of assigning variables while declaring variables.) If we can do this, then when the typeof operator returns the undefined value, we know that the variable being detected is not yet initialized, and that it has not been declared. )

Null type

The null type is the second data type with only one value, and this special value is null. From a logical point of view, a null value represents an empty object pointer, which is why the TypeOf operator detects that a null value returns ' object ', as shown in the following example:

var NULL ; alert (typeof car); // ' object '

If a defined variable is intended to be used to hold an object in the future, it is better to initialize the variable to null instead of to another value. This way, you can see if the corresponding variable has saved a reference to an object as long as you check the null value directly , as shown in the following example:

if NULL ) {    // do some action on car }

In fact, the undefined value is derived from a null value, so ECMA-262 specifies that the equality test for them returns true;

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

Here, the equality operator (= =) between null and undefined always returns true, but it is important to note that this operator translates its operands for comparison purposes (more on this later).

Although null and udefined have such relationships, their use is completely different. As mentioned earlier, it is not necessary to explicitly set the value of a variable to undefined, regardless of the circumstances, but the same rule does not apply to NULL. In other words, as long as the variable that is intended to hold the object does not actually hold the object, you should explicitly let the variable hold the null value. Doing so not only manifests null as a convention for null object pointers, but also helps to further differentiate between null and undefined.

Two, implicit conversion

+ And-

In JS, although we do not need to explicitly define the type of variable, but in the actual processing, depending on the type, there will be different processing. Let's look at a few examples:

var x = ' The answer is ' + 42; // "The answer is a"  here's ' + ' will be understood as string concatenation var y = + ' is the answer '; // "The answer"   here's ' + ' will be understood as string concatenation ' 37 ' + 7; // "377"   here the ' + ' will be understood as string concatenation ' 37 '-7; //   the '-' will be understood as the subtraction operation.

We can also skillfully use type conversion, to do something, such as to convert a variable num to a numeric type, the very simple way is to subtract the number ' 0 ', if you want to change a variable num to a string type, then you can add an empty string '.

var= num-0; alert (typeof num); // "number"num = num + '; alert (typeof num); // "string"

===

Strictly equal to A===b, first will determine the type on both sides of the equal sign, if the two sides of different types, directly return false, no longer down, if the type is the same, judge whether the value wants to wait. Be aware that nan and anything do not want to wait, including the comparison with themselves do not want to wait . In addition, the comparison ofobjects in JavaScript is compared by reference rather than by value, so comparing two objects is not equal, because it is not two identical objects. You can define the variable x (which is not differentiated), and let X and X compare to return True.

' 1.23 ' = = = ' 1.23 ';//trueNULL===NULL;//trueundefined = = undefined;//trueNULL= = = undefined;//falseNan = = = Nan;//false Nan belongs to number value, and nothing compares to waiting, including comparing with yourself and not wanting to wait.Nan = = nan;//false Nan belongs to number value, and nothing compares to waiting, including comparing with yourself and not wanting to wait.[to] = = [+];//false because the comparison of objects in JS is compared by reference, although both sides are arrays, and the same length, the same value, the same order, but also unequal, because not exactly the same object. NewObject () = =NewObject ();//false Reference comparison, two empty objects are different two objects, not equal. varx;x= = = x;//true to define the variable x, let x and X compare return True

= =

If the type is the same, the comparison method is the same as ' = = = ', and if the types are different, type conversions and comparisons are attempted:

NULL= = undefined//EqualNumber = = String//try to convert the string to number and then compare it.1.0 = = ' 1.0 ';//trueBoolean== ?//No matter what is on the right,Converts the Boolean first to a number, true to 1,false to 0, and then to the right.true= = 1;//true.Object = = Number | String//attempts to convert the object to the base type and then to compare the other cases is false.NewString (' hi ') = = ' Hi ';//trueNewBoolean (false) = = 0;//true

Third, the Packaging object

Number,string,boolean these three basic types have a corresponding package type, first look at an example:

As can be seen from the above example, JS when a basic type (such as a string type) to try to use the way the object, such as access to its length property, or add some attributes, JS will be very intelligent to the operation of the basic type to the corresponding wrapper type object, (equivalent to New String ()), the contents of this temporary wrapper object and the value of the basic type is the same, when the completion of Access or property settings, the temporary wrapper object will be destroyed, so to access the properties that have been set, is not accessible. The principle of converting number and Boolean base types to wrapper type objects is the same.

var a = ' string '; // define variable A, assignment base type ' string 'alert (a.length); // "6" creates the corresponding temporary wrapper object, accesses the length property of the temporary wrapper object, and obtains the result 6A.T = 3; //3, after the setting is successful, the temporary object is destroyed, so the following alert value is undefinedalert (A.T); //
var b = 123; b.tostring (); // "123" calls the ToString () method on the corresponding temporary wrapper object number () to convert to a string

Four, type detection

1, the most common is to use the typeof operator, will return a string, suitable for the function object and the basic type of judgment, encountered null invalidation, will return object.

typeof100//"Number" valuetypeofNaN;//"Number" valuetypeofInfinity;//"Number" valuetypeof true //"Boolean" Boolean valuetypeof(undefined);//"Undefined" indicates that the value is undefinedtypeof NewObject ();//"Object" Objectstypeof[1, 2];//an "Object" array is an object that has no special handlingtypeof NULL;//the "object" null value represents an empty object pointer, so returns an objecttypeof function //"function" from a technical point of view, functions are objects in ECMAScript, not a data type, however, functions do have some special properties, so it is necessary to differentiate functions and other objects through the typeof operator .

2, if you want to determine the object type, commonly used is instanceof, suitable for custom objects, can also be used to detect native objects, in different iframe and window detection of failure, based on the prototype chain to judge, instanceof principle: To determine whether the prototype of the Obj object chain has the prototype property of the right constructor, about the prototype chain, see the following chapter.

Obj instanceof object (obj: Must be an object and, if it is a primitive type, returns false directly; Object: Must be a function object, or a function constructor, and if not, throws a TypeError exception. )

Take a look at the simple example

 new  Object () instanceof  Array = = = Span style= "color: #0000ff;" >false  // true  [1, 2] instanceof  Array = = = true  // Span style= "color: #008000;" >true  [] instanceof  array===true  // true  

We know that any constructor has a prototype object property that will be used as a prototype of an object constructed in this way using the new constructor. For example, the person function, the function has the prototype property. When we use new person () to create a person instance, the object instance will have a prototype pointing to the Person.prototype object. We use Var bosn=new Student () to create a Student instance Bosn,bosn prototype that points to the Student object properties of its constructor prototype. When the Bosn instanceof person is detected, the Bosn.__proto__=student.prototype, and then the prototype chain continues to look up, bosn.__proto__.__proto__= Person.prototype. It will return true. Note that object type detection between different window or IFRAME cannot use instanceof!

3,Object.prototype.toString () judgment type, suitable for built-in objects and basic types, encountering null and undefined invalidation, ie6/ie7/ie8 return ' [Object object ]‘

Object.prototype.toString.apply ([]); = = = ' [Object Array] '; Object.prototype.toString.apply (function() {}); = = = ' [Object Function] '; Object.prototype.toString.apply (NULL= = = = ' [Object Null] ';//ie6/ie7/ie8 return ' [Object Object] 'Object.prototype.toString.apply (undefined); = = = ' [object undefined] ';//ie6/ie7/ie8 return ' [Object Object] 'Object.prototype.toString.apply (' 123 '); = = = "[Object String]"; Object.prototype.toString.apply (123) = = = = "[Object number]"; Object.prototype.toString.apply (true= = = = "[Object Boolean]"; Object.prototype.toString.apply (String);= = = "[Object Function]"; Object.prototype.toString.apply (Boolean);= = = "[Object Function]"

4,constructor Detection Type

Any object has a constructor attribute, inherited from the prototype, will be the constructor that constructs this object, constructor can be rewritten, use caution .

5,duck Type detection types

For example, we do not know whether an object is an array, we can determine whether the length of the object is a number, whether there are join,push and other array function methods, through the characteristics to determine whether the object is a certain type , and sometimes used.

JavaScript Data types

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.