type checking techniques widely used and not using Object.prototype.toString.call(obj).slice(8, -1) trick
https://gomakethings.com/how-to-check-if-an-object-is-an-array-with-vanilla-javascript/
//src: https://vanillajstoolkit.com/helpers/truetypeof/ | |
/*! | |
* More accurately check the type of a JavaScript object | |
* (c) 2018 Chris Ferdinandi, MIT License, https://gomakethings.com | |
* @param {Object} obj The object | |
* @return {String} The object type | |
*/ | |
var trueTypeOf = function (obj) { | |
return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase(); | |
}; | |
console.log( trueTypeOf([]) ); //"array" |
var elemCheck = {}; | |
elemCheck.isArray = function(elem) { | |
return Object.prototype.toString.call(elem).slice(8,-1) === 'Array'; | |
} | |
elemCheck.isObject = function(elem) { | |
return Object.prototype.toString.call(elem).slice(8,-1) === 'Object'; | |
} | |
elemCheck.isString = function(elem) { | |
return Object.prototype.toString.call(elem).slice(8,-1) === 'String'; | |
} | |
elemCheck.isDate = function(elem) { | |
return Object.prototype.toString.call(elem).slice(8,-1) === 'Date'; | |
} | |
elemCheck.isRegExp = function(elem) { | |
return Object.prototype.toString.call(elem).slice(8,-1) === 'RegExp'; | |
} | |
elemCheck.isFunction = function(elem) { | |
return Object.prototype.toString.call(elem).slice(8,-1) === 'Function'; | |
} | |
elemCheck.isBoolean = function(elem) { | |
return Object.prototype.toString.call(elem).slice(8,-1) === 'Boolean'; | |
} | |
elemCheck.isNumber = function(elem) { | |
return Object.prototype.toString.call(elem).slice(8,-1) === 'Number'; | |
} | |
elemCheck.isNull = function(elem) { | |
return Object.prototype.toString.call(elem).slice(8,-1) === 'Null'; | |
} | |
elemCheck.isUndefined = function(elem) { | |
return Object.prototype.toString.call(elem).slice(8,-1) === 'Undefined'; | |
} | |
console.log( elemCheck.isArray([]) ); | |
console.log( elemCheck.isObject({}) ); // true | |
console.log( elemCheck.isString('') ); // true | |
console.log( elemCheck.isDate(new Date()) ); // true | |
console.log( elemCheck.isRegExp(/test/i) ); // true | |
console.log( elemCheck.isFunction(function () {}) ); // true | |
console.log( elemCheck.isBoolean(true) ); // true | |
console.log( elemCheck.isNumber(1) ); // true | |
console.log( elemCheck.isNull(null) ); // true | |
console.log( elemCheck.isUndefined() ); // true | |
https://gomakethings.com/how-to-check-if-an-object-is-an-array-with-vanilla-javascript/