关于JavaScript中的typeof与instanceof

JavaScript中typeofinstanceof可以用来判断一个数据的类型,什么时候选择使用typeof?什么时候选择使用instanceof?

typeof运算符

typeof运算符返回值有以下几种

  • 原始数据类型
typeof 123 // "number"
typeof '123' // "string"
typeof false // "boolean"
  • 函数类型
function f() {}
typeof f
// "function"
  • undefined
typeof undefined
// "undefined"
var x
typeof x
// "undefined
  • Object
typeof window // "object"
typeof {} // "object"
typeof [] // "object"
typeof null // "object

instanceof运算符

instanceof是判断变量是否为某个对象的实例,返回值为true或false。

var o = {};
var a = [];

o instanceof Array // false
a instanceof Array // true
a instanceof Object // true

typeof 对数组 [] 和对象 {} 的返回值都是Object,无法区分数组和对象,但是instanceof可以区分。

对于什么时候该使用typeofinstanceof

  • 当变量可能为undefined的时候使用typeof运算符
alert(typeof undefinedVariable); // alerts the string "undefined"
alert(undefinedVariable instanceof Object); // throws an exception
  • 当变量可能为null的时候使用instanceof运算符
var myNullVar = null;
alert(typeof myNullVar ); // alerts the string "object"
alert(myNullVar  instanceof Object); // alerts "false"

link:
https://stackoverflow.com/questions/899574/what-is-the-difference-between-typeof-and-instanceof-and-when-should-one-be-used

https://www.jianshu.com/p/1216b1f429fb

posted @ 2019-09-12 12:34  Michelyuan  阅读(435)  评论(0编辑  收藏  举报