我是靠谱客的博主 美好发箍,这篇文章主要介绍前端面试之类型那些事(九) --- 基本类型、引用类型、类型转换、类型检测,现在分享给大家,希望可以做个参考。

最近在准备面试,感觉好些东西了解,但是了解的深度有限。自己就总结了几个模块,打算强化一下。如果你感觉我的文章对你有帮助,请点赞。如果感觉有哪些不足之处,可以留言。让我们一同进步,学习!!!
最后在说明一下,这个系列我会一直写下去。如果,你有什么好的方向,也可以提出来。

我们都知道JS是一个弱类型的语言。在过去仅仅是var代替了所有,ES6之后又引入了let,const。
虽然在写的时候,没有那么多是区别,但是实际计算的时候,该是什么还是什么。

基本类型,引用类型

总体来说,JS分为基本类型,引用类型。
基本类型:string,number,boolean,null,undefined,Symbol
引用类型:Object,Function,Array

类型转换

强调说明一下,类型转换仅仅发生在基本类型中

字符
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
let x = "1" // "string" let y = "1" // "string" x + y // "11" "string" x + ‘1’ // "11" "string" x + 1 // "11" "string" x + true // "1true" "string" x + false // "1false" "string" x + undefined // "1undefined" "string" x + null // "1null" "string" x - y // NaN "number" x - 1 // 0 "number" x - true // 0 "number" x - false // 1 "number" x - undefined // NaN "number" x - null // 1 "number"
布尔
复制代码
1
2
3
4
5
6
let x = true // true "boolean" x + true // 2 "number" x + null // 1 "number" x + undefined // NaN "number"
null,undefined
复制代码
1
2
3
4
5
6
7
8
let x = null // null "null" x + null // 0 "number" x - null // 0 "number" x - undefined // NaN "number" x + undefined // NaN "number"

**总结:**对于字符类型来说,可以与任何类型直接相加(字符串拼接)。其他类型在做操作时,包括字符串的减法操作,会按照 true 为 1,false 为 0 ,null 为 0,undefined 转化为NaN 的方法进行类型转换。针对不能进行类型转换的字符串,则直接报错。Uncaught TypeError

tips:以上测试以及总结不针对 Symbol 类型,后续会有一篇专门针对 Symbol 的文章

类型检测

常规检测方法
typeof
instanceof
Object.prototype.toString

typeof

区分基本类型,引用类型。但是null特殊,是Object

instanceof

这一块利用了原型,原型链的知识。
可以查看我之前的文章 前端面试之原型链那些事(七)那里面写的比较详细

Object.prototype.toString

所有的数据类型都可以用 Object.prototype.toString 来检测,而且非常的精准。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
var a = 123; console.log(Object.prototype.toString.call(a)); // [object Number] var b = "string"; console.log(Object.prototype.toString.call(b)); // [object String] var c = []; console.log(Object.prototype.toString.call(c)); // [object Array] var d = {}; console.log(Object.prototype.toString.call(d)); // [object Object] var e = true; console.log(Object.prototype.toString.call(e)); // [object Boolean] var f = null; console.log(Object.prototype.toString.call(f)); // [object Null] var g; console.log(Object.prototype.toString.call(g)); // [object Undefined] var h = function () {}; console.log(Object.prototype.toString.call(h)); // [object Function] var A = new Number(); console.log(Object.prototype.toString.call(A)); // [object Number]

最后

以上就是美好发箍最近收集整理的关于前端面试之类型那些事(九) --- 基本类型、引用类型、类型转换、类型检测的全部内容,更多相关前端面试之类型那些事(九)内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(56)

评论列表共有 0 条评论

立即
投稿
返回
顶部