前端最基础面试题:说说JavaScript中如何判断数据类型?

112 阅读1分钟

1. 基本数据类型的判定:typeof [变量名]

typeof 1 // 'number'
typeof 'string呀' // 'string'
typeof true // 'boolean'
typeof Symbol('abc')  // 'symbol'

控制台验证: 原始数据类型

2. 引用类型 object 的判断: ① constructor ② instanceof ③ Object.prototype.toString.call()

也可以说是数组和对象的区分方法。

var arr=[];//arr.constructor Array
var obj={};//obj.constructor Object
//在控制台输入
arr.constructor
"ƒ Array() { [native code] }"

arr instanceof Array
"true"

obj.constructor
"ƒ Object() { [native code] }"

[] instanceof Array
"true"

obj instanceof Object
"true"

注意:{} instanceof Object会报错,可能是函数的{},用变量obj接受,如图: 在这里插入图片描述

Object.prototype.toString.call():

Object.prototype.toString.call([])
"[object Array]"

Object.prototype.toString.call({})
"[object Object]"

Object.prototype.toString.call(123)
"[object Number]"

Object.prototype.toString.call('123')
"[object String]"

Object.prototype.toString.call(true)
'[object Boolean]'

Object.prototype.toString.call(undefined)
'[object Undefined]'

Object.prototype.toString.call(null)
'[object Null]'

Object.prototype.toString.call(Symbol())
'[object Symbol]'

3. 两个特殊类型用typeof 的结果:

特殊类型 null为object是历史遗留问题,js最初是这么设计的。有兴趣的自行查找资料。

4. 补充:新增数据的类型 BigInt,仍属于基本数据类型:

JS 中的Number类型只能安全地表示 -9007199254740991 和 9007199254740991, 即-(2^53-1)到 (2^53-1) 之间的整数,任何超出此范围的整数值都可能失去精度。

Number.MAX_SAFE_INTEGER
// 9007199254740991
Number.MIN_SAFE_INTEGER
// -9007199254740991
let bigN=Number.MAX_SAFE_INTEGER // bigN 为 9007199254740991
typeof bigN
// 'number'

如图: 最大最小值

失去精度的数

本文同步CSDN发布,同一作者:清颖