ES6 中提出了许多新特性,比如 let / const关键字、模板字符串、解构赋值、扩展运算符、箭头函数、for…of循环、Set、Promise等;
像我比较常用的有模板字符串、let / const 关键字声明变量和常量、箭头函数、Promise对象和新增的一些方法,比如字符串中的startsWith、padStart、padEnd,数组中的find方法查找元素、enties()方法和for…of循环结合遍历数组,Number中的 isNaN方法、对象中的Object.assign()方法用来深拷贝对象;
typeof:typeof 算是最常见的了,使用它会返回一个字符串,适合函数、对象和基本类型的判断。
console.log("测试number:"+typeof 1);
console.log("测试string:"+typeof "str");
console.log("测试false:"+typeof false);
console.log("测试null:"+typeof null);
console.log("测试undefined:"+typeof undefined);
console.log("测试Object:"+typeof new Object());
console.log("测试NaN"+typeof NaN);// Number NaN是Number类型的一个特殊值
console.log("测试数组:"+typeof [1,2,3]);// Object
console.log("测试函数类型:"+typeof function(){});// function
instanceof:返回布尔类型,使用时要注意大小写
[1,2,3] instanceof Array -------->true
new Date() instanceof Date -------->true
new Function() instanceof Function -------->true
new Function() instanceof function -------->false
null instanceof Object -------->false
Object.prototype.toString.call() :适用于所有类型的判断检测,在Object原型上返回数据格式
console.log(Object.prototype.toString.call("123")) -------->[object String]
console.log(Object.prototype.toString.call(123)) -------->[object Number]
console.log(Object.prototype.toString.call(true)) -------->[object Boolean]
console.log(Object.prototype.toString.call([1, 2, 3])) -------->[object Array]
console.log(Object.prototype.toString.call(null)) -------->[object Null]
console.log(Object.prototype.toString.call(undefined)) -------->[object Undefined]
console.log(Object.prototype.toString.call({name: 'Hello'})) -------->[object Object]
console.log(Object.prototype.toString.call(function () {})) -------->[object Function]
console.log(Object.prototype.toString.call(new Date())) -------->[object Date]
console.log(Object.prototype.toString.call(/\d/)) -------->[object RegExp]
console.log(Object.prototype.toString.call(Symbol())) -------->[object Symbol]
jquery.type() :适用于jQuery项目,据说也是万能的方法
部分摘自 js判断数据类型常用的6种方法