In Javascript, how to avoid NaN when adding arrays

◇◆丶佛笑我妖孽 提交于 2019-12-08 20:34:54

问题


I'm trying to add the values of two arrays in javascript eg. [1,2,1] + [3,2,3,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.

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.


回答1:


Use isNaN to ensure the value does not evaluate to NaN in arithmetic operations.

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);

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);



回答2:


(array1[3] || 0) + (array2[3] || 0)



回答3:


var a = [ 1, 2, 3, 4, 5 ];
var b = [ 2 , 3];
var c = [];
var maxi = Math.max(a.length, b.length);
for (var i = 0; i < maxi; i++) {
   c.push( (a[i] || 0) + (b[i] || 0) );
}



回答4:


[1,2,3] + [3,2,1]

In the above example, JavaScript converts the arrays to strings anyway so the result is:

1,2,33,2,1


来源:https://stackoverflow.com/questions/1885079/in-javascript-how-to-avoid-nan-when-adding-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!