問題描述
在算術表達式中使用字符串是否安全? (Is it safe to use strings in arithmetic expressions?)
<div class="snippet" data‑lang="js" data‑hide="false" data‑console="true" data‑babel="false">
const result = +'5';
console.log(result, typeof(result));</code></pre> </div > </div> </p>
在文檔中我只找到了關於 Number() 構造函數。
我的問題是:對字符串使用算術是否安全(加法除外)?我可以依賴上面顯示的行為嗎?
/div> </div> </p> 在文檔中我只找到了關於 Number() 構造函數。
我的問題是:對字符串使用算術是否安全(加法除外)?我可以依賴上面顯示的行為嗎?
/div> </div> </p> 在文檔中我只找到了關於 Number() 構造函數。
我的問題是:對字符串使用算術是否安全(加法除外)?我可以依賴上面顯示的行為嗎?
在字符串上使用算術是否安全(加法除外)?我可以依賴上面顯示的行為嗎?</p> 在字符串上使用算術是否安全(加法除外)?我可以依賴上面顯示的行為嗎?</p>
參考解法
方法 1:
Yes, it is safe. All arithmetic operations except a binary +
will convert the operands to numbers. That includes bitwise operators as well as unary plus.
With that said, it is probably a good idea not to rely on this extensively. Imagine that you have this code:
function calculate(a, b) {
return a * 2 + b * 3;
}
//elsewhere in the code
console.log(calculate("5", "2"));
This works fine because both a
and b
are multiplied, so are going to be converted to numbers. But in six months time you come back to the project and realise you want to modify the calculation, so you change the function:
function calculate(a, b) {
return a + b * 3;
}
//elsewhere in the code
console.log(calculate("5", "2"));
...and suddenly the result is wrong.
It is therefore better if you explicitly convert the values to numbers if you want to do arithmetic. Saves the occasional accidental bug and it is more maintainable.
方法 2:
Yes, but you have to be careful...
console.log('5.3' * 3);
console.log('5.3' + 3);
These two very similar functions cast the values different ways:
*
can only be applied between two numbers, so '5.3'
becomes 5.3
+
can also concatenate strings, and the string comes first, so 3
becomes '3'
If you understand all these you can do this, but I'd recommend against it. It's very easy to miss and JS has a lot of weird unexpected casts.
(by anotherOne、VLAZ、Keith)
參考文件