JS Data Type Detection Summary

Source: Internet
Author: User

Tag: Character expression creates an object pointer to a REG PROTOTYPE statement block UNC return

In JS, there are four ways to detect data types, namely:

    • typeof operators used to detect data types
    • Instanceof detects if an instance belongs to a class
    • Constructor constructor function
    • Object.prototype.toString.call () ToString method for object objects on the prototype chain

Let's take a look at the applicable scenarios and limitations of the above four methods respectively.

typeof operators used to detect data types

Using typeof to detect data types, the return value is in string format. The data types that can be returned are: "Number", "string", "Bolean", "undefined", "function", "Object".

<script>Console.log (typeof(1));// NumberConsole.log (typeof(' Hello '));//stringConsole.log (typeof(true));//BooleanConsole.log (typeof(undefined));//undefinedConsole.log (typeof(NULL));//ObjectConsole.log (typeof({}));//ObjectConsole.log (typeof(function() {}));//function</script>

Limitations:

    • typeof (NULL); "Object". This is because in JS, thenull value represents an empty object pointer , which is why the "object" is returned when using the TypeOf operator to detect null values.
    • Cannot specify whether the subdivision is an array or a regular, or another value in the object, because using typeof to detect the data type, for all values of the object data type, the last return is "object"
Instanceof detects if an instance belongs to a class

Instanceof is mainly used to compensate for the limitation that TypeOf cannot detect which object it belongs to .

<script>    = [N/a    ]; =/\w/;     instanceof Array);    // true    instanceof Object);    // true    instanceof REGEXP);    // true    instanceof Object);    // true</script>

Limitations:

    • cannot be used to detect and manipulate primitive data type values created by literal methods, that is, raw data types
    • Instanceof features: As long as the object on the prototype chain of the current instance, we detect with it is true
    • In the prototype inheritance of a class, the result we finally detected is not necessarily correct.
Constructor constructor function

is a property on a function prototype that points to the constructor itself.

The role and instsnceof are very similar, unlike instanceof, which can handle not only reference data types, but also raw data types .

<script>    =;     = {};     = = number); // true    Console.log (Obj.constructor = = Object); // true</script>

But one thing to note is that when used directly (object literal or raw data). Constructor, it's best to add (). For the sake of understanding, let's look at an example.

<script>    1.constructor = = = number;        // error, Invalid or unexceped token    (1). constructor = = = number;        // true    {}.constructor = = = number;        // error, Invalid or unexceped token    ({}). constructor = = number;    // true</script>

This is mainly due to the internal parsing method of JS, JS will parse 1.constructor into decimal, which is obviously unreasonable, the decimal point should be the number, so it will cause an error. JS will parse {} into a statement block to execute, then a decimal point appears later is obviously unreasonable, so will also error. To solve this problem, we can add () to the expression to enable JS to parse correctly.

Limitations: We can rewrite the prototype of the class, in the process of rewriting it is likely to overwrite the previous constructor, so that the result is not accurate detection

<script>     function  Fn () {};     New Array;     var New Fn;     // F is a function, which makes sense that his constructor should be function, but after modifying its prototype chain, its constructor becomes an array.    Console.log (F.constructor = = Array);    // true</script>
Object.prototype.toString.call () ToString method for object objects on the prototype chain

The function of Object.prototype.toString is to return the details of the class to which the execution body of the current method belongs (this in the method) , which is the most comprehensive and commonly used method of detecting data types.

the type of the return value is of type string .

<script>Console.log (Object.prototype.toString.call (1));//[Object number]Console.log (Object.prototype.toString.call (/^sf/));//[Object RegExp]Console.log (Object.prototype.toString.call ("Hello"));//[Object String]Console.log (Object.prototype.toString.call (true));//[Object Boolean]Console.log (Object.prototype.toString.call (NULL));//[Object Null]Console.log (Object.prototype.toString.call (undefined));//[Object Undefined]Console.log (Object.prototype.toString.call (function() {}));//[Object Function]Console.log (typeof(Object.prototype.toString.call (function() {})));//string</script>

JS Data Type Detection Summary

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.