How to detect various types of JavaScript _javascript tips

Source: Internet
Author: User
Tags hasownproperty

First, introduce the next 5 kinds of original types

5 of the original types in JavaScript are string, Number,boolean,undefined,null

var name = "Jack";
var age =;
var single = false;
var app;  Undefined

Console.log (typeof name);  String
Console.log (typeof age);  Number
Console.log (typeof single);//boolean
Console.log (typeof app);  Undefined
console.log (typeof null);  Object

4 other basic types, except null , are found to be identified with typeof :

if (typeof name = = = "string") {name = + "Zhang";}
if (typeof age = = = "Number") {age++}
if (typeof single = = "Boolean" && single) {...}
if (typeof app = = "undefined") {app = {};}

Because typeof null gets object, NULL is detected directly with = =:

if (el = = null) {...}

Second, the object

JavaScript objects include built-in objects (date,regexp, Error, and so on) and custom Objects .

(Note that function and array are also built-in objects, but the next section is separate)

Objects cannot be detected with typeof as a basic type, because the detected result is object:

Console.log (typeof new Date ());  Object
Console.log (typeof new RegExp ());//object
Console.log (typeof new Error ());  Object
Console.log (typeof new Person ())/////object is also object with typeof detection

To use instanceof to detect:

var date = new Date ();
var reg = new RegExp ();
var err = new Error ();
var me = new Person ();

if (date instanceof date) {  //detection date Year
  = Date.getfullyear (); 
}
if (reg instanceof RegExp) {  //detection of regular expression
  reg.test (...); 
}
if (err instanceof Error) {  //Detect exception
  throw err; 
}
if (Me instanceof person) {  //Detect custom Objects
  ... 
}

However, there is a problem with the custom object, assuming that the person is defined in both the browser Framea and the Frameb. The Me object is defined in Framea and me instanceof Person is true with detection. But when the custom object me passes to Frameb, the instanceof is false in Frameb.

As you can see from the beginning of this section, function and array are also built-in objects, but remain in the next section. The reason is that the function and array also have the same problem as the custom object. therefore function and array are generally not instanceof

Third, Function

It says that using instanceof to detect function cannot cross frame. Therefore, the typeof is used to detect that it can cross frame:

var func = function () {};
if (typeof func = = = ' function ') {...}

But IE8 previously used typeof to detect DOM system functions to get object, so IE8 used to in:

Console.log (typeof document.getElementById);    object, not function
Console.log (typeof document.getelementsbytagname);//object, not function
Console.log ( typeof document.createelement);     object, not function

//ie8 previous IE browser, to use in to detect whether the DOM function
if ("getElementById" in document) {...}    
is supported. if ("getElementsByTagName" in document) {...}
if ("createelement" in document) {...}

Four, Array

It says that using instanceof to detect array cannot span frame. Custom detection methods before ES5. One of the most accurate methods: The dependent array's ToString returns the fixed string "[Object Array]" to detect the fact that:

function IsArray (arr) {return
  Object.prototype.toString.call (arr) = = "[Object Array]";
}

The method is precise and elegant, so it is adopted by many libraries, and finally the array is introduced as the IsArray method in ES5, referring to MDN. Now you don't need a custom detection method, just use IsArray () .

Other detection methods, are each defective, not 100% accurate. But as a way of thinking can be used for reference. For example, the dependency array is the only object that contains the sort method to detect:

function IsArray (arr) {return
  typeof Arr.sort = = "function";
}

If the custom object also defines the sort method, the method fails.

Five, attributes

Detects whether a property should be hasOwnPropertyin an instance object. If you don't care whether the attribute is in an instance object or in a prototype object, you can simply click in

For example, to detect literal object properties:

var person = {
  Name: "Jack",
  age:33
};
if ("name" in person) {...}         True
if (Person.hasownproperty ("name")) {...}  True

For example, instance object properties:

var person = function (name, age) {
  this.name = name;
  This.age = age;
Person.prototype.location = "Shanghai";

var me = new Person ("Jack")
if ("name" in me) {...}         True
if (Me.hasownproperty ("name")) {...}  True
if ("Location" in me) {...}       True
if (Me.hasownproperty ("location")) {...} False

Otherwise, other methods are not good:

if (Object[propname])      //not Good, how do you know that the attribute value is not 0 or 1?
if (object[propname] = = null)    //not Good, how do you know that the attribute value is not null?
if (object[propname] = = undefined)  //not good, how do you know that the attribute value is not undefined?

Summarize

Detection of string,number,boolean,undefined,function with typeof

detecting null with = = =

Detecting array with IsArray ()

Detecting built-in objects (except function and array) and custom objects with instanceof

Use hasOwnProperty to detect whether the property is in the instance object. If you don't care whether the attribute is in an instance object or in a prototype object, you can simply click in

OK, this article describes how to detect various types of JavaScript content is here, I hope you can seriously learn the content of this article, perhaps for everyone to learn JavaScript help.

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.