数据类型

根本类型

String、Number、Boolean、Null、Undefined

援用类型

Object、Array、Function

判断数据类型的形式

1. 应用 typeof

typeof 'test'          // stringtypeof 1880            // numbertypeof true            // booleantypeof null            // objecttypeof undefined       // undefinedtypeof {}              // objecttypeof []              // objecttypeof function() {}   // function

毛病:判断根本类型还是能够的,判断援用类型作用就没那么大了。无奈校验数组、对象、Null

2. 应用 constructor

let xiaoming = 'text';xiaoming.constructor   // String(){}let xiaoming = 1880;xiaoming.constructor   // Number(){}let xiaoming = true;xiaoming.constructor   // Boolean(){}let xiaoming = null;xiaoming.constructor   // 报错let xiaoming = undefined;xiaoming.constructor   // 报错let xiaoming = {};xiaoming.constructor   // Object(){}let xiaoming = [];xiaoming.constructor   // Array(){}let xiaoming = function() {};xiaoming.constructor   // Function(){}

毛病:无奈校验 Null 和 Undefined

3. 应用 instanceof

function A() {}function A1() {}function B() {}A1.prototype = new A(); // A1 继承 Alet xiaoming = new A1(); // 实例化console.log(xiaoming instanceof A); // trueconsole.log(xiaoming instanceof A1); // trueconsole.log(xiaoming instanceof B); // false

毛病:只实用于判断对象属于什么类型,其余的都不太实用

4. 应用 Object.prototype.toString.call()

Object.prototype.toString.call('text');            // [object String]Object.prototype.toString.call(1880);              // [object Number]Object.prototype.toString.call(true);              // [object Boolean]Object.prototype.toString.call(null);              // [object Null]Object.prototype.toString.call(undefined);         // [object Undefined]Object.prototype.toString.call({});                // [object Object]Object.prototype.toString.call([]);                // [object Array]Object.prototype.toString.call(function() {});     // [object Function]

目前比拟精确的一种形式

文章的内容/灵感都从下方内容中借鉴

  • 【继续保护/更新 500+前端面试题/笔记】https://github.com/noxussj/In...
  • 【大数据可视化图表插件】https://www.npmjs.com/package...
  • 【利用 THREE.JS 实现 3D 城市建模(珠海市)】https://3d.noxussj.top/