js basis: judgment type

Keywords: Javascript JSON JQuery

I. common examples

Judge whether it is an object

let obj = {}

// 1.Object.prototype.toString

if (Object.prototype.toString.call(obj) === '[Object Object]') {
    console.log('Object!')
}

// 2.constructor

if (obj.constructor === Object) {
    console.log('Object!')
}

// 3.$.type() 

if ($.type(obj) === 'object') {
    console.log('Object!')
}

// 4. $. Isplaninobject(), used to determine whether the specified parameter is a pure object

if ($.isPlainObject(obj) === 'object') {
    console.log('Object!')
}

Judge whether the object is empty

let obj = {}

// 1.JSON

if (JSON.stringify(obj) === '{}') {
    console.log('Empty object!')
}

// 2. Object. Keys(), the ES6 method returns an array of enumerable properties of a given object

if (Object.keys(obj).length === 0) {
    console.log('Empty object!')
}

// 3. cycle

for (var i in obj) { 
    return true // Not empty
}
return false // Empty object

// 4. $.isEmptyObject(), the object has no attributes that can be iterated through for...in

if ($.isEmptyObject(obj)) {
    console.log('Empty object!')
}

Determine whether it is an array

let arr = []

// 1.Object.prototype.toString

if (Object.prototype.toString.call(arr) === '[object Array]') {
    console.log('Array!')
}

// 2.constructor

if (arr.constructor === Array) {
    console.log('Array!')
}

// 3.$.type() 

if ($.type(arr) === 'array') {
    console.log('Array!')
}

// 4.Array.isArray, when detecting array instances, Array.isArray is better than instanceof, because Array.isArray can detect iframes

if (arr instanceof Array === true) {
    console.log('Array!')
}
//Array.isArray is introduced by ES 5.1 and does not support ie6-8. If Array.isArray() does not exist, running the following code before other code creates the method
if (!Array.isArray) {
  Array.isArray = function(arg) {
    return Object.prototype.toString.call(arg) === '[object Array]';
  };
}

// 5.instanceof

if (arr instanceof Array === true) {
    console.log('Array!')
}

Determine whether it is an array or an empty array

let arr = []

// 1.length, simple version, known as array

if (arr && arr.length > 0) {
    console.log('Not empty array!')
} else {
    console.log('Empty array!')
}

// 2.Object.prototype.isPrototypeOf, to test whether one object exists in the prototype chain of another object

if (Object.prototype.isPrototypeOf(arr) && Object.keys(arr).length === 0) {
    console.log('Empty array!')
}

// 3.Array.isArray, there are also compatibility problems

if (Array.isArray(arr) && arr.length === 0) {
    console.log('Empty array!')
}

Judge string as json

function isJSON(str) {
    if (typeof str == 'string') {
        try {
            var obj=JSON.parse(str);
            if(typeof obj == 'object' && obj ){
                return true; // Rotatable
            }else{
                return false;// Not to turn
            }

        } catch() {
            return false; // Not to turn
        }
    }
    console.log('It is not a string!')
}

Determine whether the string is a number

let num = '3'

// 1.isNaN, null, space and empty string will be processed as 0

if ((!isNaN(num)) && num != null && num != '') {
    console.log('num For numbers!')
}

// 2. regular

function isNumber(val) {
    var regPos = /^\d+(\.\d+)?$/; //Nonnegative floating point number
    var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //Negative floating point number
    if(regPos.test(val) || regNeg.test(val)) {
        return true;
    } else {
        return false;
    }
}

Judge a value as null or undefined

// jquery source recommended writing method, save code
var obj = {}
if(obj.a == null) {
    //Equivalent to obj. A = = = null | obj. A = = = undefined
}

2. Five common methods

1.typeof

Operator returns a string representing the type of the uncomputed operand, which is used to determine the general type except null, object and array

2.Object.prototype.toString

Primitive prototype extension function, used to accurately distinguish data types, versatile

3.$.type()

Used to determine the type of JavaScript built-in objects, and return the type name in lowercase form, universal

4.instanceof

This operator is used to test whether the prototype property of the constructor appears anywhere in the prototype chain of the object, to detect the judgment method of reference type, and to judge for Array and RegExp.

5.constructor

This property returns a reference to the array function that created the object, and each object with a prototype automatically gets the constructor property.

Note: problems with class inheritance

 function A(){};

 function B(){};

 A.prototype = new B(); //A inherited from B

 var aObj = new A();

 alert(aobj.constructor === B) //true;

 alert(aobj.constructor === A) //false;

//Both direct and indirect inheritance of objects in the instanceof method will report true

alert(aobj instanceof B) //true;

alert(aobj instanceof A) // true;

//To solve the problem of constructor, it is usually to let the constructor of the object point to itself manually

aobj.constructor = A; //Assign your own class to the constructor property of the object

alert(aobj.constructor === A) // true;

alert(aobj.constructor === B) // false; the base class will not report true;

Yuan Bo: https://blog.csdn.net/u011684...

Reference resources: typeofinstanceof$.type][8],[$.isPlainObject()Judge as json

Posted by thatsgreat2345 on Sat, 30 Nov 2019 04:41:21 -0800