JS数据类型、数据类型判断

目录

数据类型

基本数据类型

复杂数据类型

数据类型判断

typeof

Object.prototype.toString

instanceof

Array.isArray 方法

总结


数据类型

基本数据类型

String(字符串)Number(数字)Boolean(布尔)Undefined(未定义)Null(空)Symbol(独一无二的值)BigInt(大整数)

复杂数据类型

Object(Map、Set、Person)Array(数组)Function(函数)

数据类型判断

typeof

js提供了typeof 能够很准确的判断基本数据类型,对于数组或者Map, Set这种数据类型不能够很友好的进行判断.

typeof 42; // "number"
typeof 'hello'; // "string"
typeof true; // "boolean"
typeof undefined; // "undefined"
typeof null; // "object"
typeof Symbol(1)  // "symbol"
typeof BigInt(1)  // "bigint"
typeof {}; // "object"
typeof []; // "object"
typeof new Map()  // "object"
typeof new Set()  // "object"
typeof function() {}; // "function"
Object.prototype.toString

对于js内置的数据类型都能判断,比如Array、Set、Map、Null,但是对于自定义的类无法做判断

Object.prototype.toString.call(42); // "[object Number]"
Object.prototype.toString.call('hello'); // "[object String]"
Object.prototype.toString.call(true); // "[object Boolean]"
Object.prototype.toString.call(undefined); // "[object Undefined]"
Object.prototype.toString.call(null); // "[object Null]"
Object.prototype.toString.call(Symbol(1)); // "[object Symbol]"
Object.prototype.toString.call(BigInt(1)); // "[object BigInt]"
Object.prototype.toString.call({}); // "[object Object]"
Object.prototype.toString.call([]); // "[object Array]"
Object.prototype.toString.call(new Set()); // "[object Set]"
Object.prototype.toString.call(new Map()); // "[object Map]"
Object.prototype.toString.call(function() {}); // "[object Function]"

function Person(){}   // 自定义类
const p = new Person()

class Animal {    // 自定义类
    construtor(){}
}
const cat = new Animal ()
Object.prototype.toString.call(cat); // "[object Object]"
Object.prototype.toString.call(new p()); // "[object Object]"

instanceof

运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上,只做复杂数据类型的判断

{} instanceof Object; // true
[] instanceof Array; // true
function() {} instanceof Function; // true

function Person(){}
const p = new Person()

class Animal {
    construtor(){}
}
const cat = new Animal ()

cat instanceof Animal;  // true
p instanceof Person;   // true
new Map() instanceof Map;   // true
new Set() instanceof Set;   // true
Array.isArray 方法

判断一个值是否是数组

Array.isArray([]); // true
Array.isArray({}); // false
Array.isArray('hello'); // false

总结

如果要判断基本数据类型可以用typeof、如果判断复杂数据类型可以用instanceof

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值