typeof和instanceof

typeof一般用于检测基本类型,而对引用类型的检测一般用 instanceof

typeof和instanceof属于运算符,和+  -  *  /是一样的。

typeof的返回值是字符串包括:'number'、'string'、'boolean'、'undefined'、'object'、'function'。它有两种写法:typeof 1 和 typeof(1)。

数字类型、NAN,typeof返回的值是number。比如说:typeof(1),返回值是number;

字符串类型,typeof返回的值是string。比如typeof(“123”返回值时string);

布尔类型,typeof返回的值是boolean。比如typeof(true)返回值时boolean;

对象、数组、null返回的值是object。比如typeof(window),typeof(document),typeof(null)返回的值都是object;

函数类型,返回的值是function。比如:typeof(eval),typeof(Date)返回的值都是function;

不存在的变量、函数或者undefined,将返回undefined。比如:typeof(abc)、typeof(undefined)都返回undefined;

typeof null  // 'object'
typeof function() {}    // 'function'
typeof NaN   // 'number'
typeof ''   // 'string'

instanceof运算符可以判断一个变量是否是某个对象(类)的实例,返回值是布尔类型

instanceof在判断数组是,即会把数组当做Array类型,又会把数组当做Object类型,都会返回true

object.prototype.tostring.call()

Object.prototype.toString.call(fn);   // "[object Function]"
Object.prototype.toString.call(date);   // "[object Date]"
Object.prototype.toString.call(arr);   // "[object Array]"
Object.prototype.toString.call(reg);   // "[object RegExp]"

// 基本数据类型
Object.prototype.toString.call(null);   // "[object Null]"
Object.prototype.toString.call(undefined);   // "[object Undefined]"
Object.prototype.toString.call(“abc”);   // "[object String]"
Object.prototype.toString.call(123);   // "[object Number]"
Object.prototype.toString.call(true);   // "[object Boolean]"

判断数组

1 用Array.isArray(arr)可以判断数组;

2 Object.prototype.toString.call(arr);

判断函数

Object.prototype.toString.call(fn); 

typeof(fn);

判断对象

Object.prototype.toString.call(obj);

 

posted @ 2019-08-27 10:38  seeBetter  阅读(279)  评论(0)    收藏  举报