5 ways to judge the data type

1. typeof

  • Can determine the data type, it returns a string representing the data type (the returned result can only include number, boolean, string, function, object, undefined);
  • You can use typeof to determine whether a variable exists (such as if (typeof a! = "Undefined") {...});
  • The problem with the Typeof operator is that it returns object no matter what type the referenced object is
typeof {} // object
typeof  [1,2] // object
typeof /\s/ //object

2.instanceof

The principle is because A instanceof B can determine whether A is an instance of B, and returns a Boolean value. The data type is determined by the construction type.

console.log (arr instanceof Array); // true 
console.log (date instanceof Date); // true 
console.log (fn instanceof Function); // true 
// Note: The instanceof must be followed by the object type, not case Wrong, this method tries some conditional selection or branch

3. Judge by toString.call () method under Object

Object.prototype.toString.call();
console.log(toString.call(123)); //[object Number]
console.log(toString.call('123')); //[object String]
console.log(toString.call(undefined)); //[object Undefined]
console.log(toString.call(true)); //[object Boolean]
console.log(toString.call({})); //[object Object]
console.log(toString.call([])); //[object Array]
console.log(toString.call(function(){})); //[object Function]

4. Judging by the contructor of the object

console.log('数据类型判断' -  constructor);
console.log(arr.constructor === Array); //true
console.log(date.constructor === Date); //true
console.log(fn.constructor === Function); //true

5. JQ method to determine the data type

jQuery provides a series of tool methods to determine the data type to make up for the shortcomings of JavaScript's native typeof operator. The following method judges the parameter and returns a boolean value.
jQuery.isArray (); whether it is an array
jQuery.isEmptyObject (); whether it is an empty object (without enumerable properties).
jQuery.isFunction (): whether it is a function
jQuery.isNumberic (): whether it is a number
jQuery.isPlainObject (): whether it is an object generated using "{}" or "new Object", not an object natively provided by the browser.
jQuery.isWindow (): Whether it is a window object;
jQuery.isXMLDoc (): Determine whether a DOM node is in an XML document.


Author: 8d2855a6c5d0
link: https: //www.jianshu.com/p/967d6db70437
Source: Jane books

Guess you like

Origin www.cnblogs.com/passkey/p/12757589.html