JS判断数据类型的方法

JavaScript 的数据类型

  • string:字符串
  • number:数字
  • boolean:布尔值
  • undefined:未定义
  • null:空值
  • object:对象(包括数组和函数)
  • symbol:符号,独一无二的值(ES6新增)

一、typeof的缺陷

typeof 可以判断 stringnumberbooleanundefinedsymbolfunction 等类型,不可以判断 nullobject 类型。

var str = "Hello";
var num = 123;
var bool = true;
var undf;
var nl = null;
var obj = {name: "John", age: 25};
var arr = [1, 2, 3];
var func = function() {};
var sym = Symbol("mySymbol");

console.log(typeof str);    // 输出:string
console.log(typeof num);    // 输出:number
console.log(typeof bool);   // 输出:boolean
console.log(typeof undf);   // 输出:undefined
console.log(typeof nl);     // 输出:object
console.log(typeof obj);    // 输出:object
console.log(typeof arr);    // 输出:object
console.log(typeof func);   // 输出:function
console.log(typeof sym);    // 输出:symbol

注意:typeof 无法区分 nullObjectArray。typeof 判断这三种类型返回都是 ‘object’。

二、判断是否为数组

方法1

使用 instanceof 可以判断数据是否为数组。

[] instanceof Array // true

需要注意的是, instanceof 不可以用来判断是否为对象类型,因为数组也是对象。

[] instanceof Object // true
{} instanceof Object // true

方法2

constructor 也可以判断是否为数组。

[].constructor === Array // true

方法3

Object.prototype.toString.call() 可以获取到对象的各种类型。

Object.prototype.toString.call([]) === '[object Array]' // true
Object.prototype.toString.call({}) === '[object Object]' // true

此方法还可以用来判断是否为 promise 对象。

let obj = new Promise()
Object.prototype.toString.call(obj) === '[object Promise]' // true

方法4

使用数组的 isArray() 方法判断。

Array.isArray([]) // true

方法5

Object.getPrototypeOf(val) === Array.prototype // true 

三、判断是否为对象

方法1(推荐)

Object.prototype.toString.call() 可以获取到对象的各种类型。

Object.prototype.toString.call({}) === '[object Object]' // true

方法2

Object.getPrototypeOf(val) === Object.prototype // true 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

温其如玉_zxh

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值