How to detect various types of JavaScript

  • 2021-07-06 10:04:01
  • OfStack

1. First introduce the next five original types

The five original types of JavaScript are string, number, boolean, undefined and null


var name = "Jack";
var age = 32;
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

It is found that the other four basic types except null can be identified by 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 will get object, null is directly detected with ===:


if(el === null) {  …  }

2. Objects

Objects for JavaScript include built-in objects (Date, RegExp, Error, and so on) and custom objects.

(Note that Function and Array are both built-in objects, but they are discussed separately in the next section.)

Objects can't be detected with typeof like basic types, because the detected results are all object:


console.log(typeof new Date());  //object
console.log(typeof new RegExp()); //object
console.log(typeof new Error());  //object
console.log(typeof new Person()); // Use typeof Detecting custom objects is also object

To use instanceof instead for detection:


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

if(date instanceof Date) {  // Test date 
  year = date.getFullYear(); 
}
if(reg instanceof RegExp) {  // Detecting regular expressions 
  reg.test(...); 
}
if(err instanceof Error) {  // Detection anomaly 
  throw err; 
}
if(me instanceof Person) {  // Detect custom objects 
  ... 
}

However, there is a problem with custom objects, assuming that Person is defined in both browsers frameA and frameB. me object is defined in frameA, using me instanceof Person true was detected. But when the custom object me is passed to frameB, instanceof will be false in frameB.

As mentioned at the beginning of this section 1, Function and Array are both built-in objects, but they will be left to the next section. The reason is that Function and Array have the same problems as custom objects. Therefore, instanceof is not used for Function and Array1

3. Function

It is said above that Function cannot be detected across frame with instanceof. Therefore, it is detected with typeof, which can be used across frame:


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

However, IE8 previously used typeof to detect DOM function to obtain object, so IE8 previously used in instead:


console.log(typeof document.getElementById);    //object No, it's not function
console.log(typeof document.getElementsByTagName); //object No, it's not function
console.log(typeof document.createElement);     //object No, it's not function

//IE8 Previous IE Browser, you want to use it instead in To detect whether it supports DOM Function 
if("getElementById" in document) {  …  }    
if("getElementsByTagName" in document) {  …  }
if("createElement" in document) {  …  }

4. Array

It is said above that Array cannot be detected across frame with instanceof. Before ES5, the detection method was customized. One of the most accurate methods: The fact that toString, which relies on Array, returns a fixed string "[Object Array]" is used to detect:


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

This method is precise and elegant, so it has been adopted by many libraries. Finally, it was introduced into Array as isArray method in ES 5, referring to MDN. Now you don't need to customize the detection method, just use isArray ().

Other detection methods have their own defects and cannot be 100% accurate. But as a way of thinking, it can be used for reference. For example, depending on the fact that Array is the only object that contains sort methods:


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

If a custom object also defines the sort method, the method is invalid.

5. Attributes

Check whether the attribute should use hasOwnProperty in the instance object. If you don't care whether the attribute is in the instance object or the prototype object, you can simply use in

For example, detecting literal object attributes:


var Person = {
  name: "Jack",
  age: 33
};
if("name" in Person) {  …  }         //true
if(Person.hasOwnProperty("name")) {  …  }  //true

For example, instance object properties:


if(typeof name === "string") { name += "Zhang"; }
if(typeof age === "number") { age++; }
if(typeof single === "boolean" && single) {  …  }
if(typeof app === "undefined") { app = {}; }
0

Other methods are not good:


if(typeof name === "string") { name += "Zhang"; }
if(typeof age === "number") { age++; }
if(typeof single === "boolean" && single) {  …  }
if(typeof app === "undefined") { app = {}; }
1

Summarize

string, number, boolean, undefined and Function were detected by typeof

Detection of null with = = =

Detection of Array by isArray ()

Detecting built-in objects (except Function and Array) and custom objects with instanceof

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

Ok, this article introduces how to detect various types of JavaScript content that's all. I hope you can seriously study the content of this article, which may be helpful for you to learn JavaScript.


Related articles: