16. js 判断变量类型,包括ES6 新类型Symbol
相信大家在开发中遇到需要判断变量类型的问题,js变量按存储类型可分为值类型和引用类型,值类型包括Undefined、String、Number、Boolean,引用类型包括object、Array、Function,
直接上辨别类型的封装函数
function varType(n) { var typeStr = Object.prototype.toString.call(n); //var typeOfName = (typeof n); var typeName = ''; switch (typeStr){ case '[object String]': typeName = 'string'; break; case '[object Number]': typeName = 'number'; break; case '[object Boolean]': typeName = 'boolean'; break; case '[object Undefined]': typeName = 'undefined'; break; case '[object Object]': typeName = 'object'; break; case '[object Array]': typeName = 'array'; break; case '[object Null]': typeName = 'null'; break; case '[object RegExp]': typeName = 'RegExp'; break; case '[object Symbol]': typeName = 'symbol'; break; case '[object JSON]': typeName = 'json'; break; case '[object Math]': typeName = 'math'; break; default: typeName = 'object'; } return typeName; }; console.log(varType("1")); console.log(varType(1)); console.log(varType({})); console.log(varType([])); console.log(varType(function () {})); console.log(varType(null)); console.log(varType(undefined)); console.log(varType(true)); console.log(varType(NaN)); console.log(varType(Symbol())); console.log(varType(JSON)); console.log(varType(Date)); console.log(varType(Math)); console.log(varType(RegExp()));