JavaScript中数据类型的判断

数据类型判断的常用方法

以下所有结果,由nodejs执行所得。

1. typeof

The typeof operator returns a string indicating the type of the unevaluated operand.
typeof返回操作对象的类型(字符串表示)。
语法:

typeof 操作对象
typeof(操作对象)

示例:

let str = new String('abc');
let array = [1,2,3];

console.log(typeof 8);//"number"
console.log(typeof "s");//"string"
console.log(typeof str);//object
console.log(typeof true);//"boolean"
console.log(typeof null);//"object"	
console.log(typeof a);//undefined
console.log("==> Array:" + typeof array);//object

上述示例中,typeof null可参考https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/typeof#typeof_null
特殊值:

console.log(typeof undefined);//"undefined"
console.log(typeof NaN);//"number"

总结:typeof除了可以判断基本的数据类型外,还可以判断undefinedNaN的类型。

2. instanceof

The instanceof operator tests to see if the prototype property of a constructor appears anywhere in the prototype chain of an object. The return value is a boolean value.
instanceof操作符用于检测构造器的prototype属性是否在一个对象的原型链中。从中可以看出,instanceof无法用于基本数据类型的检测。

示例:

console.log([1,2,3] instanceof Object);//true
console.log(Function instanceof Object);//true
console.log(Array instanceof Object);//true

//null,undefined不在Object原型链中
console.log(undefined instanceof Object);//false
console.log(null instanceof Object);//false

3. null与undefined

null是一个字面值,表示变量不指向任何对象。

The global undefined property represents the primitive value undefined. It is one of JavaScript's primitive types.

undefined是原始的数据类型。一个全局的undefined属性表示原始值undefined

  • undefinednull仅字面值相等。
console.log(undefined == null);//true
console.log(undefined === null);//false
  • undefined可以使用typeof来进行判断。
  • undefined另一种表示方式void 0
console.log(void 0);//undefined

参考文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值