字符串与数字运算中加号的特殊表现及数学加法实现方法
如何实现字符串与数字的真正数学加法
在JavaScript中,除加号(+)外,减(-)、乘(*)、除(/)等运算符都会自动将字符串转换为数字执行数学运算,但加号会优先执行字符串拼接。以下测试代码的结果能直观体现这一特性:
let first = "2" + 2 let second = 4 + 4 let third = first + second console.log(third)
输出:228
let first = "2" + 2 let second = 4 + 4 let third = first - second console.log(third)
输出:14
let first = "2" + 2 let second = 4 + 4 let third = first * second console.log(third)
输出:176
let first = "2" + 2 let second = 4 + 4 let third = first / second console.log(third)
输出:2.75
要实现字符串与数字的真正数学加法,核心是先将字符串显式转换为数字类型,再执行加法运算,常用方法如下:
使用
Number()函数转换:直接将字符串转为数字后相加let first = Number("2") + 2; // 结果为4 let second = 4 + 4; // 结果为8 let third = first + second; console.log(third); // 输出:12使用一元加号(
+)转换:在字符串前添加+,快速完成类型转换let first = +"2" + 2; // 结果为4 let second = 4 + 4; // 结果为8 let third = first + second; console.log(third); // 输出:12使用
parseInt()/parseFloat()转换:适合处理包含非数字内容的字符串(纯数字字符串场景下效果与前两种一致)let first = parseInt("2") + 2; // 结果为4 let second = 4 + 4; // 结果为8 let third = first + second; console.log(third); // 输出:12
如果是对已拼接完成的字符串变量(比如示例中first是"22")执行加法,同样需要先转换类型再运算:
let first = "2" + 2; // 此时first为字符串"22" let second = 4 + 4; let third = Number(first) + second; // 先转数字再相加 console.log(third); // 输出:30
内容的提问来源于stack exchange,提问作者Quadron LT
相关产品推荐
相关产品推荐

