JS 数据类型判断

JS 数据类型判断

一、JS 数据类型

javascript 有11种数据类型,分别为:

  1. Null:
  2. Undefined:
  3. Number: 数字
  4. Date: 日期
  5. String: 字符串
  6. Boolean: 布尔
  7. Function: 函数
  8. RegExp: 正则表达式
  9. Array: 数组
  10. Object: 对象
  11. Symbol: ES6引入了一种新的原始数据类型Symbol,表示独一无二的值

二、判断 数据类型

  1. typeof
typeof 1           //number
typeof 'a'         //string
typeof true        //boolean
typeof undefined   //undefined
typeof null        //object
typeof {}          //object
typeof [1,2,3]     //object
function Fn(){}
typeof new Fn()    //object
typeof new Array() //object
  1. instanceof
function A(name,age){
  this.name = name;
  this.age = age;
}
a = new A('张三',18);
console.log(a instanceof A)  //true

obj = new Object()//创建一个空对象obj
//或者通过字面量来创建:
obj = {}
console.log(obj instanceof Object); // true
 
arr = new Array()  //创建一个空数组arr  或arr = []
console.log(arr instanceof Array ); // true
 
date = new Date()
console.log(date instanceof Date ); // true
 
// 注意:instanceof后面一定要是对象类型,instanceof前面相当于它的实例对象,
// 后面的对象类型大小写不能写错,该方法试用一些条件选择或分支
  1. constructor【建议使用】
    • 这种方式解决了instanceof的弊端,可以检测出除了undefined和null的9种类型(因为它两没有原生构造函数)
let num = 23;
let date = new Date();
let str = "biu~";
let reg = new RegExp();
let bool = true;
let fn = function () {
  console.log(886);
};
let udf = undefined;
let nul = null;
let array = [1, 2, 3];
console.log(num.constructor); // [Function: Number]
console.log(date.constructor); // [Function: Date]
console.log(str.constructor); // [Function: String]
console.log(bool.constructor); // [Function: Boolean]
console.log(fn.constructor); // [Function: Function]
console.log(reg.constructor); // [Function: RegExp]
console.log(array.constructor); // [Function: Array]

若有凝问或错误,请指出,我好及时改正,让我们一起进步!
email : binary_space@126.com
qq : 103 586 2795
敲门砖: 代码谱写人生

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

征客

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

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

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

打赏作者

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

抵扣说明:

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

余额充值