javascript - 为什么要在 try- 和 catch-phrase 中实现相同的功能?
问题描述
我试图理解我在继承的 JavaScript 代码中发现的舍入函数:
function percentageWithCommas(x?) {
try {
return (x * 100).toLocaleString("en-UK", {
maximumFractionDigits: 1, minimumFractionDigits: 1 }) + '%';
} catch (e) {
return (x * 100).toFixed(2) + '%';
}
}
我知道现在 JS 中的舍入是用.toLocaleString(...)
而不是.toFixed()
.
为什么要在 thetry
和catch
短语中实现相同的东西?
参考
解决方案
双重实现似乎没用:toLocaleString()
与旧浏览器的兼容性很高,请参阅
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
不同的问题:你不应该使用(x?)
,因为如果x
是可选的,你会遇到null * 100
. 您最好测试 x 是否为数字并执行以下操作:
function percentageWithCommas(x) {
if(isNaN(x)) return '';
return (x * 100).toLocaleString("en-UK", {
maximumFractionDigits: 1, minimumFractionDigits: 1 }) + '%';
}
或类似的东西。
注意:如果您担心它.toLocalString
不可用,您可以使用 明确检查它的存在if ((0).toLocaleString)
。