typeof 与 instanceof的简单的应用

typeof 与 instanceof的简单的应用

比较数据类型

  • 比较简单的数据类型 ==typeof==

typeof 运算符把类型信息当作字符串返回。typeof 返回值有六种可能: "number," "string," "boolean," "object," "function," 和 "undefined."
我们可以使用typeof来获取一个变量是否存在

==示例:==

console.log( typeof arr == Integer);
// Numbers
typeof 37 === 'number';
typeof 3.14 === 'number';
typeof(42) === 'number';

// Strings
typeof "bla" === 'string';

// Booleans
typeof true === 'boolean';

// Undefined
typeof undefined === 'undefined';
 
// Functions
typeof function(){} === 'function';
typeof class C {} === 'function';
typeof Math.sin === 'function';

复制代码

对于Array,Null等特殊对象使用typeof一律返回object,这正是typeof的局限性。

如果我们希望获取一个对象是否是数组,或判断某个变量是否是某个对象的实例则要选择使用instanceof。

  • 比较复杂的数据类型 ==instanceof==

instanceof用于判断一个变量是否某个对象的实例,instanceof 左操作数是一个类,右操作数是标识对象的类。

instanceof 运算符是用来测试一个对象是否在其原型链原型构造函数的属性。其语法是 object instanceof constructor

console.log(arr instanceof Array);

var a=new Array();
alert(a instanceof Array);	//true,
alert(a instanceof Object)//true


function test(){};
var a=new test();
alert(a instanceof test)	//true。


复制代码

转载于:https://juejin.im/post/5ce50a0cf265da1ba56af4e6

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值