对存在JavaScript隐式类型转换的四种情况的总结(必看篇)

一般存在四种情况,JavaScript会对变量的数据类型进行转换。

目录

rush:xhtml;"> * if中的条件会被自动转为Boolean类型 * 会被转为false的数据 * 会被转为true的数据 * 参与+运算都会被隐式的转为字符串 * 会被转为空字符串的数据 * 会被转为字符串的数据 * 会被转为数据类型标记的数据 * 参与*运算都会被隐式的转为数字 * 会被转为0的数据 * 会被转为1的数据 * 会被转为NaN的数据 * == 运算符 * 为true的时候 * 为false的时候

if中的条件会被自动转为Boolean类型

会被转为false的数据

rush:xhtml;"> if(false) console.log(2333) if('') console.log(2333) if(null) console.log(2333) if(undefined) console.log(2333) if(NaN) console.log(2333)

会被转为true的数据

rush:xhtml;"> if(true) console.log(2333) // 2333 if('test') console.log(2333) // 2333 if([]) console.log(2333) // 2333 if({}) console.log(2333) // 2333

参与+运算都会被隐式的转为字符串

会被转为空字符串的数据

rush:xhtml;"> 'str-' + '' // str- 'str-' + []

会被转为字符串的数据

rush:xhtml;"> 'str-' + '1' // "str-1" 'str-' + 1 // "str-1" 'str-' + false // "str-false" 'str-' + true // "str-true" 'str-' + null // "str-null" 'str-' + undefined // "str-undefined" 'str-' + NaN // "str-NaN"

会被转为数据类型标记的数据

rush:xhtml;"> 'str-' + {} // "str-[object Object]" 'str-' + {a:1} // "str-[object Object]"

参与*运算都会被隐式的转为数字

会被转为0的数据

rush:xhtml;"> 2 * '' // 0 2 * [] // 0 2 * false // 0

会被转为1的数据

rush:xhtml;"> 2 * '1' // 2 2 * [1] // 2 2 * true // 2

会被转为NaN的数据

rush:xhtml;"> 2 * {} // NaN 2 * {a:1} // NaN

== 运算符

为true的时候

rush:xhtml;"> 0 == false // true 0 == '' // true 0 == '0' // true 0 == [] // true 0 == [0] // true

1 == true // true
1 == '1' // true
1 == [1] // true

[1] == true // true
[] == false // true

为false的时候

rush:xhtml;"> 0 == {} // false 0 == null // false 0 == undefined // false 0 == NaN // false

1 == {} // false
1 == null // false
1 == undefined // false
1 == NaN // false

[] == [] // false
[1] == [1] // false
[1] == {} // false
[1] == {a:1} // false
[1] == false // false
[1] == null // false
[1] == undefined // false
[1] == NaN // false

{} == {} // false
{a:1} == {a:1} // false

注:

空数组[],在+运算符下是转为空字符串'',在*运算符下是转为数字0。但在if语句中,则转为true。

以上这篇对存在JavaScript隐式类型转换的四种情况的总结(必看篇)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持编程之家。

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...