Talk about JavaScript variable type and variable type detection

Source: Internet
Author: User
Tags object object true true

JavaScript is a weakly typed language, which is a typical example of a variable that can be assigned to any type when it is used. So let's take a look at JavaScript, which has a way of using these variable types already.

Let's take a look at the types of javascript:

String---Strings
Number---Value
Boolean---bool value
Undefined---an unspecified variable or declaration is not assigned a value
NULL---NULL
Object---Objects
Function---Functions

It is more controversial here that the function type should not be attributed to the variable type inside. For details, see
The "basic type" argument in JavaScript

These data types can be divided into 2 kinds: 1, original type (string, number, Boolean, null, undefined) 2, object (except that the original type is an object)

Now let's look at the 2 ways JavaScript creates variables: 1, object creation 2, literal creation

The first object type creates var str =new String (' Tudou '), var num =new number (123), VAR bool =new Boolean (True), Console.log (typeof Str,type     of NUM, BOOL);           Object Object Boolean//second literal way str = ' Tudou '; num = 123;bool =true;console.log (typeof str,typeof num, bool); String number True

look at the red boxes where they are objects and inherit their respective data types. the first is to create the data from a class that corresponds to a new one, so that you get an object of the corresponding data type. Let's look at the breakpoint in front of the first Console.log ():
PS: You can create changes by passing different data types directly through New Object (), and JavaScript automatically determines what data type you need to create by passing in the values you pass in.

The second is to create the data by means of a literal, which describes the representation of a fixed value in the code. This gets the direct amount of a data:
You can see that the data is purely data, nothing else. That is, the above STR itself cannot invoke any function because it is a "data" instead of an object, which means that the operation of the string is possible in such a way:

var str = ' abc '; strstr (str, ' a ');

we often write in javascript: This is a bit cumbersome and troublesome, not convenient. So JavaScript introduces the wrapper type.

var str = ' abc '; Str.indexof (' a ')

var str1 =new String (' abc '), var str2 = Str.indexof (' a '); str1 =null;return str2;

The processing of some of these columns allows us to use the literal creation of the variable to invoke the object's method, greatly increasing the convenience of the operation. So how does it do that pinch? When we execute the Str.indexof () method, JavaScript does the following conversion
1. Create an object instance of type String
2. Call the IndexOf () method on an instance of an object
3. Destroy this object instance
The code might look like this:

Here are some basic types of JavaScript variables, 2 ways to create variables, and wrapper types now look at how we determine what a variable is in JavaScript.

First look at the following code:

var str = "a"; var num = 1;var bool =true;var arr = [];var obj = {};var Undef;var nul =null;log (typeof str,typeof Num,typeof Bool,typeof obj,typeof arr,typeof nudef,typeof nul); Arr =new Array (n/a), obj =new Object (), str =new String (' a '), num =new number (1), bool =new Boolean (TRUE), and log ("<br>"   ); log (typeof str,typeof num,typeof bool,typeof obj,typeof arr,typeof nudef,typeof nul);    function log () {for (var i=0; i<arguments.length; i++) {document.write (arguments[i]+ "\ t"); }}

Its output data is:
String number Boolean Object object undefined object
Object Object Object Object object undefined object
The typeof operator detects a variable, so long as the variable is a reference type, it returns object so when you create a base database type using the New keyword, typeof returns all object, so you can't use typeof to detect the data type. Then there's no other way.

JavaScript also provides a way to detect an instance of an object instanceof maybe, probably, you can try it.

var str = "a"; var num = 1;var bool =true;var arr = [];var obj = {};var Undef;var nul =null;log (strinstanceof String, Numins tanceof number, boolinstanceof Boolean, Objinstanceof object), arr =new Array (n/a), obj =new Object (), str =new String (' a ' Num =new Number (1), bool =new Boolean (True), log ("<br>"); log (strinstanceof String, numinstanceof number,  Boolinstanceof Boolean, objinstanceof Object);    function log () {for (var i=0; i<arguments.length; i++) {document.write (arguments[i]+ "\ t"); }}

var str = ' a '; var str1 =new String (' a '); Console.log (Object.prototype.toString.call (str), Object.prototype.toString.call (STR1));

its output is: The output of it is:
False False True
True true True to True
The instanceof is used to identify the type of object being processed. Unlike the TypeOf method, the Instanceof method requires the developer to explicitly confirm that the object is of a particular type. This can only detect if the variable is an instance of an object, nor does it meet our needs.

If you want to implement type detection in JavaScript, you need to use Object.prototype.toString.call (str);

[Object String] [Object String] they are consistent. Then we can determine the object type based on this.

We can do simple processing of them to expose them to the global window, so that we could use them later.

Var typelist = ' string number boolean array object date function  RegExp '. Split ('   '),     tostring = object.prototype.tostring;for (var i= 0; i<typelist.length; i++) {     (function (index) {         window[' is ' +typelist[index]] =function (obj) {             var reg =new regexp (Typelist[index])              return reg.test (Tostring.call (obj));         };    }) (i);     }var  str = ' abc '; var num = 1;var bool =true;var obj = {};var date  =new date (); Var arr = [];var reg = /abc/;console.log (isString (str),  isnumber (num), &NBSP;ISBOOlean (BOOL),  isobject (obj),  isdate (date),  isarray (arr),  isregexp (reg));       //trueconsole.log (IsObject (num));     //false

The above is a summary of the individual, the wrong place please point out thank you.

Talk about JavaScript variable type and variable type detection

Related Article

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.