英文:
Is this right way to convert data attributes values to number in javascipt? Need to get valid numeric value or 0
问题
以下是要翻译的内容:
我正在使用以下代码将数据属性值转换为数字。我希望在所有情况下都能获得有效的数字值或0。例如,如果数据属性值为空(""),那么在那种情况下我需要0。这是为了避免因为我在计算中使用结果而得到NaN。
Number($("td[id^='tdCumulativeUnderOverSpendPrevious']").data("val") || 0);
英文:
I am using the following code to convert data attribute values to Numbers. I want to get a valid numeric value or 0 in all cases. e.g if the data attribute value is blank("") then I need 0 in that case. The intention is to avoid getting NaN because I am using the result in calculations.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
Number($("td[id^='tdCumulativeUnderOverSpendPrevious']").data("val") || 0);
<!-- end snippet -->
答案1
得分: 3
我建议将 || 0
移到 Number()
调用的外部。您希望将元素的数据转换为数字,因此只应将该数据传递给 Number()
。如果该值无法解析,Number()
将返回 NaN
,然后您才希望将整个结果更改为 0
。
在 Number()
调用内部使用 || 0
可能会产生意想不到的后果,因为它将任何假值转换为零,而不仅仅是无法转换为数字的值。
另外,考虑使用 parseFloat()
而不是 Number()
。Number()
将转换任何可能转换的值,但 parseFloat()
更加严格。例如,Number(true)
是 1
,但 parseFloat(true)
是 NaN
。
这是我会使用的代码:
// 设置数据为数字
$('div').data('val', '100');
const num1 = parseFloat($('div').data('val')) || 0;
console.log(num1);
// 设置数据为非数字
$('div').data('val', 'hello');
const num2 = parseFloat($('div').data('val')) || 0;
console.log(num2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div></div>
英文:
I'd recommend moving the || 0
to the outside of the Number()
call. You want to convert the element's data to a number, so you should pass only that into Number()
. Number()
will return NaN
if that value can't be parsed, and only then do you want to change the whole thing into 0
.
Using || 0
inside of the Number()
call might have unintended consequences depending because it will change any falsy value into zero, not just a value that can't be converted to a number.
Also, consider using parseFloat()
instead of Number()
. Number()
will convert any value that can possible be converted, however parseFloat()
is stricter. For example, Number(true)
is 1
, but parseFloat(true)
is NaN
.
Here's the code that I'd use:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
// set data to number
$('div').data('val', '100')
const num1 = parseFloat($('div').data('val')) || 0;
console.log(num1);
// set data to not a number
$('div').data('val', 'hello')
const num2 = parseFloat($('div').data('val')) || 0;
console.log(num2);
<!-- language: lang-html -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div></div>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论