Using typeof to judge the data type in JavaScript can only distinguish the basic types , namely "number", "string", "undefined", "boolean", and "object" .
For arrays, functions, and objects , the relationship is intricate, and typeof will uniformly return the "object" string.
How to judge complex types such as objects, arrays, and functions?
To distinguish objects, arrays, and functions, simply using typeof is not enough. In JavaScript, you can use the Object.prototype.toString method to judge.
Object.prototype.toString()
The function of the toString method is to return the string form of an object. By default, the type string is returned . Therefore, it can be used to determine the type of a value.
like:
var o = {};
o.toString(); // "[object Object]"
The above code calls the method of the empty object toString
, and the result returns a string object Object
, the second of which Object
represents the constructor of the value. This is a very useful way to determine the data type.
However, arrays, strings, functions, and Date objects each override their own version of toString
the method and override Object.prototype.toString
the method.
var arr = [];
arr.toString(); //''
[1, 2, 3].toString() // "1,2,3"
'123'.toString() // "123"
We found that the instance object may customize toString
the method and override Object.prototype.toString
the method. Through call
the method of functions, methods can be called on any value Object.prototype.toString
to help us determine the type of this value.
Object.prototype.toString.call(value)
example:
var arr = [];
console.log(Object.prototype.toString.call(arr))
// "[object Array]"
Since everything in JavaScript is an object and nothing is an exception, applying the Object.prototype.toString.call() method to all value types results in the following:
console.log(Object.prototype.toString.call(123)) //[object Number]
console.log(Object.prototype.toString.call('123')) //[object String]
console.log(Object.prototype.toString.call(undefined)) //[object Undefined]
console.log(Object.prototype.toString.call(true)) //[object Boolean]
console.log(Object.prototype.toString.call({})) //[object Object]
console.log(Object.prototype.toString.call([])) //[object Array]
console.log(Object.prototype.toString.call(function(){})) //[object Function]
Extension: implement the function of judging the object type
//判断是否为函数
function isFunction(it) {
return Object.prototype.toString.call(it) === '[object Function]';
}
//判断是否为数组:
function isArray(o) {
return Object.prototype.toString.call(o) === '[object Array]';
}