JS 数据类型判断
一、JS 数据类型
javascript 有11种数据类型,分别为:
- Null:
- Undefined:
- Number: 数字
- Date: 日期
- String: 字符串
- Boolean: 布尔
- Function: 函数
- RegExp: 正则表达式
- Array: 数组
- Object: 对象
- Symbol: ES6引入了一种新的原始数据类型Symbol,表示独一无二的值
二、判断 数据类型
- 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
- 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前面相当于它的实例对象,
// 后面的对象类型大小写不能写错,该方法试用一些条件选择或分支
- 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
敲门砖: 代码谱写人生