在Javascript中,如何在添加数组时避免使用NaN [英] In Javascript, how to avoid NaN when adding arrays
问题描述
我正在尝试在javascript中添加两个数组的值,例如。 [1,2,1] + [3,2,3,4]
I'm trying to add the values of two arrays in javascript eg. [1,2,1] + [3,2,3,4]
答案应该是4,4,4,4但我要么得到4 ,4,4或4,4,4,NaN,如果我将第一个数组长度更改为4.
The answer should be 4,4,4,4 but I'm either getting 4,4,4 or 4,4,4,NaN if I change the 1st array length to 4.
我知道第4个数字需要在第1个数组中,但我无法弄清楚如果没有数字,如何告诉javascript使其为0而不是未定义。
I know a 4th number needs to be in the 1st array, but i can't figure out how to tell javascript to make it 0 rather then undefined if there is no number.
推荐答案
使用 isNaN
确保该值不会计算为<$算术运算中的c $ c> NaN 。
Use isNaN
to ensure the value does not evaluate to NaN
in arithmetic operations.
这将安全地添加两个数字,如果其中一个不是数字,它将用0代替。
This will safely add two numbers such that if one of them is not a number, it will be substituted with 0.
var c = (isNaN(a) ? 0 : a) + (isNaN(b) ? 0 : b);
如果您怀疑a或b可能是字符串而不是数字(2
而不是 2
),您必须在添加之前将其转换为数字。您可以使用一元 +
来执行此操作。
If you suspect that either a or b could be a string instead of number ("2"
instead of 2
), you have to convert it into number before adding it. You can use a Unary +
to do it.
var c = (isNaN(a) ? 0 : +a) + (isNaN(b) ? 0 : +b);
这篇关于在Javascript中,如何在添加数组时避免使用NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!