JS中常用的数学运算
- 除了加法外,都是数学运算,如果遇到非数字类型,先基于Number此案转换为数字类型,再运算
- 一些转换
true 1
false 0
null 0
‘’ 0
[] 0 //Number([])是数字0,因为[]是对象,先要转化为字符串‘’,然后转换为数字0;但是如果在+中,在转换为‘’后就变成字符串拼接了,到不了数字的运算
undefined NaN
symbol不能转
console.log(10 - null) //=>10
console.log(3 * undefined) //=>NaN
console.log(3 + undefined) //=>NaN
console.log("3" + undefined) //=>"3undefined"
console.log(true - "12") //=>11
- 加法既有数学运算,也有字符串拼接(只要加号任意一边出现字符串,则变为字符串拼接),此时对象还是要转换为字符串后拼接
对象转化为数字(先转化为字符串,再转化为数字)
console.log(3 - "2px")//=> 3- NaN = NaN
console.log(3 + "3px")//=> "33px"
console.log(1 + "1")//=> "11"
console.log(1 + {})//=> "1[object Object]"// 在把{}转化为数字的过程中,先把他转化为字符串”[object Object]“,然后加号一边出现了字符串,此时变为字符串拼接
console.log(1 + [])//=>"1"(字符串“1”) []是对象,先把[]转换为字符串“”,此时一边出现字符串,然后变成了字符串拼接
console.log([10] + true)//=>"10true"[10]是对象,先把[10]转换为字符串“10”,然后加号一边出现了字符串,此时变为字符串拼接
console.log(true + [10])//=>"true10"
- NaN
字符串拼接练习
let a = 100 + ture + 21.2 + null + undefined + "Tencent" + [] + null + 9 + false
/*
* 100 + true => 101
* 101 + 21.2 => 122.2
* 122.2 + null => 122.2 + 0 => 122.2
* 122.2 + undefined => 122.2 + NaN => NaN
* NaN + "Tencent" => "NaNTencent" 字符串拼接,此后都是字符串拼接
* "NaNTencent" + [] = "NaNTencent" + "" => "NaNTencent"
* "NaNTencent" + null => "NaNTencentnull"
* "NaNTencentnull" + 9 = "NaNTencentnull" + "9" => "NaNTencentnull9"
* "NaNTencentnull9" + false = "NaNTencentnull9" + "false" = "NaNTencentnull9false"
*/
//==============
let a = 10 + null + true + [] + undefined + 'abc' + null + [] + 10 + false;
/*
* 10 + null -> 10 + 0 -> 10
* 10 + true -> 10 + 1 -> 11
* 11 + [] -> 11 + '' -> '11' 空数组变为数字,先要经历变为空字符串,遇到字符串,啥都别想了,直接变为字符串拼接
* '11' + undefined -> '11undefined'
* ...
* '11undefinedabcnull10false'
*/
本文深入探讨JavaScript中的数学运算规则,包括基本算术运算、特殊类型的处理方式以及字符串拼接与数学运算之间的转换机制。特别关注不同数据类型在运算前的转换过程,如布尔值、空值、未定义值和符号的转换,以及对象如何被转化为数字或字符串进行运算。
297

被折叠的 条评论
为什么被折叠?



