前端架构系列

数据类型的细节知识

2020-08-12  本文已影响0人  羽晞yose

本文代码全是题目,用于检验知识掌握程度,简单的不会解析,直接给答案

数据类型

数据类型检测

typeof 特点

面试题:

let a = typeof typeof typeof [12, 23]
console.log(a); // 'string'

Number类型

NaN

特点:NaN和任何类型值都不相等,NaN和自身也不相等
判断:isNaN 用于判断是否为NaN

let res = parseFloat('left: 200px');
if (res === 200) {
    alert(200)
} else if (res === NaN) {
    alert(NaN)
} else if (typeof res === 'number') {
    alert('number') // 'number'
} else {
    alert('Invaild Number')
}

解析:parseFloatparseInt的特点是接收一个字符串,从左到右进行查找(遇到非有效数字字符则停止查找),如果处理的不是字符串,会先转换为字符串再进行查找,如果结束是没有找到任何有效数字,则返回NaN。所以res = NaN,NaN和任何类型值都不相等,但它是个数值类型,所以会输出'number'

把其他数据类型转换为数字的方法

parseInt('') // NaN
Number('') // 0
isNaN('') // '' => 0,false
parseInt(null) // NaN
Number(null) // 0
isNaN(null) // isNaN(0) => false
parseInt('12px') // 12
Number('12px') // NaN
isNaN('12px') // true
parseFloat('1.6px') + parseInt('1.2px') + typeof parseInt(null)
// 1.6 + 1 + typeof NaN => '2.6Number'
isNaN(Number(!!Number(parseInt('0.8'))))
// !!Number(0) => Number(0) => false
typeof !parseInt(null) + !isNaN(null)
// typeof true + !isNaN(0) => 'boolean' + true => 'booleantrue'

// 压轴题
let res = 10 + false + undefined + [] + 'Tencent' + null + true + {}
console.log(res)
/**
 * 10 + false => 10 + 0 => 10
 * 10 + undefined => 10 + Number(undefined) => 10 + NaN => NaN
 * NaN + [] => NaN + '' => 'NaN'
 * NaN + 'Tencent' => 'NaNTencent'
 * 'NaNTencent' + null + true => 'NaNTencentnulltrue'
 * 'NaNTencentnulltrue' + {} => 'NaNTencentnulltrue' + ({}).toString() =>
 * 'NaNTencentnulltrue' + '[object Object]' =>
 * 'NaNTencentnulltrue[object Object]'

+加号

特点:遇到字符串(或者对象,因为对象就是先转换为字符串然后再处理),那么就不是数值运算,而会转变成字符串拼接

==转换规律

上一篇 下一篇

猜你喜欢

热点阅读