微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/js/36742.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐