js array and determines whether native toString () method determines the data type

Array.isArray()

A = the let [l, 2,3] 
Array.isArray (A); to true // 
This method is a new method ES5, compatibility problems than unsupported Es5
if (!Array.isArray) {
  Array.isArray = function(arg) {
    return Object.prototype.toString.call(arg) === '[object Array]';
  };
}
Object.prototype.toString.call () determines the type of data

1. The basic types:

Object.prototype.toString.call(null);//”[object Null]”
Object.prototype.toString.call(undefined);//”[object Undefined]”
Object.prototype.toString.call(“abc”);//”[object String]”
Object.prototype.toString.call(123);//”[object Number]”
Object.prototype.toString.call(true);//”[object Boolean]”

2. Analyzing original reference type:

Function Type
Function fn(){console.log(“test”);}
Object.prototype.toString.call(fn);//”[object Function]”
Date Type
var date = new Date();
Object.prototype.toString.call(date);//”[object Date]”
Array type
var arr = [1,2,3];
Object.prototype.toString.call(arr);//”[object Array]”
Regular Expressions
var reg = /[hbc]at/gi;
Object.prototype.toString.call(arr);//”[object RegExp]”
Custom Types
function Person(name, age) {
    this.name = name;
    this.age = age;
}
var person = new Person("Rose", 18);
Object.prototype.toString.call(person); //”[object Object]”
Clearly this method can not accurately determine the person is an instance of the Person class, but can only use the instanceof operator to judge, as follows:
console.log (person instanceof Person); // output is true

3. Analyzing native JSON object:

&& Object.prototype.toString.call window.JSON isNativeJSON = var (JSON); 
the console.log (isNativeJSON); // output is "[object JSON]" Description JSON is native, or not 

original author: Keepup ~
Original
address: https://www.cnblogs.com/cn-chy-com/p/11524980.html
 

Guess you like

Origin www.cnblogs.com/lpp-11-15/p/12445643.html