Javaascript Data Type Judgment

Keywords: Javascript JQuery github IE

JavaScript has six types of data, which can be divided into primitive type (aka basic type) and object type (aka reference type).

There are five primitive types: number, string, boolean, undefined and null.

Common object types are Function, Array, Date, and regular

ES6 Added Symbol

Judgment of pleasure provided by JavaScript itself

type

If you don't make a strict distinction between objects, use type.

number:

typeof 1; // "number"

string:

typeof 'hello world'; // "string"

boolean:

typeof true; // "boolean"

undefined:

typeof undefined; // "undefined"

null:

typeof null; //  "object"

object:

typeof {};  // "object"

Symbol:

typeof Symbol(); // "symbol"

Null is handled separately, as in jQuery, and if the object to be judged is null, it returns String(obj) directly.

Therefore, it is possible to write a method of judging basic types:

var type = function(obj) {
    if(obj === null) return String(obj);
    return typeof obj;
}

instanceof

instanceof is a method used to specify that an object is of a particular type.

The implementation of instanceof uses prototype inheritance L for left expression and R for right expression. It uses whether L.proto equals R.prototype to judge the type of object.

String:

var str = new String('hello world');

str instanceof String // true

String:

var str = new Number('10');

str instanceof String // true

Datte:

var o = new Date();

o instanceof Date; // true

Array:

var o = new Array();

o instanceof Array; // true

RegExp:

var reg = new RegExp('/^[a-z]$/');

reg instanceof RegExp; // true

Object:

var o = new Object();

o instanceof Object; // true

var o2 = {};

o2 instanceof Object; // true

Function:

var o = function() {};

o instanceof Function; // true

Func (custom):

function Func() {}

var o = new Func();

o instanceof Func; // true

instanceof can validate both custom objects and built-in object types, but one thing to note is that they are objects themselves.

var str = new String('hello world');

str instanceof Object; // true

We explained the implementation principle of instanceof at the beginning, knowing that the left side of instanceof is the right side of the instance, so we can get the type name of the object with the following code:

obje.__proto__.constructor.name;

Therefore, we can write a method to judge the object type as follows:

objectType = function(obj) {
    if(typeof obj === 'object' || typeof obj === 'function') {
        return obj.__proto__.constructor.name;
    }
}

The above method is good, but the ie browser does not support u proto_ (this property is also our common way to judge browsers and non-browsers).

Here's an all-purpose approach.

Object.prototype.toString.call(obj)

Object.prototype.toString.call('hello world'); // "[object String]"

Object.prototype.toString.call(1); // "[object Number]"

Object.prototype.toString.call(true); // "[object Boolean]"

Object.prototype.toString.call(null); // "[object Null]"

Object.prototype.toString.call(); // "[object Undefined]"

Object.prototype.toString.call([]); // "[object Array]"

Object.prototype.toString.call({}); // "[object Object]"

Object.prototype.toString.call(new Date()); // "[object Date]"

Object.prototype.toString.call(/test/i); // "[object RegExpArray]"

Object.prototype.toString.call(function () {}); // "[object Function]"

The code to get the data type is as follows:

var core_toString = Object.prototype.toString;
var getObjectType = function(obj) () {
    return core_toString.call(obj).slice(8, -1);
}

This method can judge all data types and is officially recommended, but in actual development, we use typeof to judge basic types and Objet.prototype.toString.call(obj) to judge reference types.

Real Data Type Judgment of Common Frameworks and Libraries

jQuery:

var class2type = {};
var core_toString = Object.prototype.toString;

"Boolean Number String Function Array Date RegExp Object Error".split(' ').forEach(function(name, i) {
    class2type["[object " + name + "]"] = name.toLowerCase();
});

var getType = function (obj) {
    if (obj == null) {
        return String(obj);
    }
    return typeof obj === "object" || typeof obj === "function" ?
        class2type[ core_toString.call(obj) ] || "object" :
        typeof obj;
};
// test
getType(function(){}); // "function"
getType([]); // "array"

Here we extract the implementation principle of jQuery and implement it with native js.

vue.js


/**
 * Determine whether it is a basic data type
 */
function isPrimitive (value) {
  return (
    typeof value === 'string' ||
    typeof value === 'number' ||
    // $flow-disable-line
    typeof value === 'symbol' ||
    typeof value === 'boolean'
  )
}

/**
 * Judging whether it is a common object
 */
function isObject (obj) {
  return obj !== null && typeof obj === 'object'
}

/**
 * Get the native type, such as: [object Object]
 */
var _toString = Object.prototype.toString;

function toRawType (value) {
  return _toString.call(value).slice(8, -1)
}

/**
 * Common object
 */
function isPlainObject (obj) {
  return _toString.call(obj) === '[object Object]'
}
/**
 * Regular object
 */
function isRegExp (v) {
  return _toString.call(v) === '[object RegExp]'
}

angular2:

function isPresent(obj) {
return obj !== undefined && obj !== null;
}
exports.isPresent = isPresent;
function isBlank(obj) {
return obj === undefined || obj === null;
}
exports.isBlank = isBlank;
function isBoolean(obj) {
return typeof obj === "boolean";
}
exports.isBoolean = isBoolean;
function isNumber(obj) {
return typeof obj === "number";
}
exports.isNumber = isNumber;
function isString(obj) {
return typeof obj === "string";
}
exports.isString = isString;
function isFunction(obj) {
return typeof obj === "function";
}
exports.isFunction = isFunction;
function isType(obj) {
return isFunction(obj);
}
exports.isType = isType;
function isStringMap(obj) {
return typeof obj === 'object' && obj !== null;
}
exports.isStringMap = isStringMap;
function isPromise(obj) {
return obj instanceof _global.Promise;
}
exports.isPromise = isPromise;
function isArray(obj) {
return Array.isArray(obj);
}
exports.isArray = isArray;
function isDate(obj) {
return obj instanceof exports.Date && !isNaN(obj.valueOf());
}
exports.isDate = isDate;

We often see these implementations, or a mixture of them (zepto.js).

JavaScript related articles github.com

Posted by nesargha on Thu, 31 Jan 2019 02:00:15 -0800