关于html:第-39-题JS-数据类型有哪些

2次阅读

共计 1616 个字符,预计需要花费 5 分钟才能阅读完成。

数据类型

根本类型

String、Number、Boolean、Null、Undefined

援用类型

Object、Array、Function

判断数据类型的形式

1. 应用 typeof

typeof 'test'          // string
typeof 1880            // number
typeof true            // boolean
typeof null            // object
typeof undefined       // undefined
typeof {}              // object
typeof []              // object
typeof 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 继承 A

let xiaoming = new A1(); // 实例化

console.log(xiaoming instanceof A); // true
console.log(xiaoming instanceof A1); // true
console.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/
正文完
 0