admin管理员组文章数量:1399847
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.
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.
Share Improve this question asked Dec 11, 2009 at 0:31 JonasJonas 1031 gold badge1 silver badge4 bronze badges4 Answers
Reset to default 9Use 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);
(array1[3] || 0) + (array2[3] || 0)
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) );
}
[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
本文标签: In JavaScripthow to avoid NaN when adding arraysStack Overflow
版权声明:本文标题:In Javascript, how to avoid NaN when adding arrays - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1739208465a2148259.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论