【JS】单感叹号 和 双感叹号 的用法

文章目录

用法

  • 双感叹号!!可以将一个值转换成对应的Boolean值,
  • 第一个感叹号!是将其转化成取反后的Boolean类型的值
  • 第二个感叹号!!是将取反后的Boolean类型的值再进行一次取反运算,才能得到自身对应真正的布尔值
  • 双感叹号!!相当于强制转换布尔类型Boolean()

示例

  1. 初始值:
console.log('初始值:')
console.log('值:',	{},			'类型:',typeof {})
console.log('值:',	[],			'类型:',typeof [])
console.log('值:',	"",			'类型:',typeof "")
console.log('值:',	NaN,		'类型:',typeof NaN)
console.log('值:',	undefined,	'类型:',typeof undefined)
console.log('值:',	null,		'类型:',typeof null)
  • 打印结果:
初始值:
值: {} 		类型: object
值: [] 		类型: object
值: "" 		类型: string
值: NaN 		类型: number
值: undefined 	类型: undefined
值: null 		类型: object
  1. 使用单感叹号(!),取反:
console.log('单感叹号:')
console.log('值:',	!{},			'类型:',typeof !{})
console.log('值:',	![],			'类型:',typeof ![])
console.log('值:',	!"",			'类型:',typeof !"")
console.log('值:',	!NaN,			'类型:',typeof !NaN)
console.log('值:',	!undefined,		'类型:',typeof !undefined)
console.log('值:',	!null,			'类型:',typeof !null)
  • 打印结果:
单感叹号:
值: false 		类型: boolean
值: false 		类型: boolean
值: true 		类型: boolean
值: true 		类型: boolean
值: true 		类型: boolean
值: true 		类型: boolean
  1. 使用双感叹号(!!),再取反,负负得正就是他本身:
console.log('双感叹号:')
console.log('值:',	!!{},			'类型:',typeof !!{})
console.log('值:',	!![],			'类型:',typeof !![])
console.log('值:',	!!"",			'类型:',typeof !!"")
console.log('值:',	!!NaN,			'类型:',typeof !!NaN)
console.log('值:',	!!undefined,	'类型:',typeof !!undefined)
console.log('值:',	!!null,			'类型:',typeof !!null)
  • 打印结果:
双感叹号:
值: true 		类型: boolean
值: true 		类型: boolean
值: false 		类型: boolean
值: false 		类型: boolean
值: false 		类型: boolean
值: false 		类型: boolean
  1. 使用Boolean()强制转换,等价于双感叹号(!!):
console.log('Boolean():')
console.log('值:',	Boolean({}),			'类型:',typeof Boolean({}))
console.log('值:',	Boolean([]),			'类型:',typeof Boolean([]))
console.log('值:',	Boolean(""),			'类型:',typeof Boolean(""))
console.log('值:',	Boolean(NaN),			'类型:',typeof Boolean(NaN))
console.log('值:',	Boolean(undefined),		'类型:',typeof Boolean(undefined))
console.log('值:',	Boolean(null),			'类型:',typeof Boolean(null))
  • 打印结果:
Boolean():
值: true 		类型: boolean
值: true 		类型: boolean
值: false 		类型: boolean
值: false 		类型: boolean
值: false 		类型: boolean
值: false 		类型: boolean
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一颗不甘坠落的流星

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值