javascript基本类型和类型检测方法

基本类型

  • String(字符串)
  • Number(数字)
  • Boolean(布尔)
  • Symbol (符号)
  • Object(对象)
    • Function(函数)
    • Array(数组)
    • Date(日期)
    • RegExp(正则)
  • null
  • undefined

检测方法 

1.typeof    无法区分 对象、 日期 、正则、 null


// 1.typeof

const str = 'str';
const num = 0;
const bool = false;
const obj = {};
const fun = function () {};
const arr = [];
const date = new Date();
const reg = new RegExp();
const symbol1 = Symbol();
const null1 = null;
const und = undefined;

typeof str // String
typeof num // Number
typeof bool // Boolean
typeof symbol1 // Symbol
typeof und // undefined
typeof fun // Function
typeof obj // Object
typeof date // Object
typeof reg // Object
typeof null1 // Object
typeof arr // Object

2. instanceof  检测一个对象在原型链中是否有构造函数prototype属性,判断的必须是实例 ,基本类型无法检测 

fun instanceof Function  // true
date instanceof Date  // true
reg instanceof RegExp  // true
arr instanceof Array  // true

3.object原型上的toString 全能型选手

Object.prototype.toString.call(str).slice(8,-1) // String
Object.prototype.toString.call(num).slice(8,-1) // Number
Object.prototype.toString.call(bool).slice(8,-1) // Boolean
Object.prototype.toString.call(symbol1).slice(8,-1) // Symbol
Object.prototype.toString.call(fun).slice(8,-1) // Function
Object.prototype.toString.call(date).slice(8,-1) // Date
Object.prototype.toString.call(reg).slice(8,-1) // RegExp
Object.prototype.toString.call(arr).slice(8,-1) // Array
Object.prototype.toString.call(null1).slice(8,-1) // Null
Object.prototype.toString.call(und).slice(8,-1) // Undefined

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值