Easy question: I'm trying to add a number to an array like this:
sorted[4][2]+=nbrMvt[i];
but it adds the two numbers as if they were strings. The output just puts the numbers one beside the other... I have tried these methods:
sorted[4][2]+=parseInt(nbrMvt[i]);
sorted[4][2]=sorted[4][2]+nbrMvt[i];
sorted[4][2]=parseInt(sorted[4][2])+parseInt(nbrMvt[i]);
But none of them work.
[EDIT]
Ok, here is how I created my array:
var sorted = MultiDimensionalArray(13,4);
I then atribute string values to the sorted[x][0...12]
the last example gives me "NaNNaNNaNNaN"
function MultiDimensionalArray(iRows,iCols)
{
var i;
var j;
var a = new Array(iRows);
for (i=0; i < iRows; i++)
{
a[i] = new Array(iCols);
for (j=0; j < iCols; j++)
{
a[i][j] = "";
}
}
return(a);
}
(btw, what should I understand from the vote down on my question?)
3 Answers 3
You may not have set some value (perhaps i === null or somthing) ... But this works:
var sorted = [],
nbrMvt = [],
i = 0;
// set up arrays and populate just enough values...
nbrMvt[i] = 40;
sorted[4] = [];
sorted[4][2] = 2;
sorted[4][2]=parseInt(sorted[4][2])+parseInt(nbrMvt[i]);
document.write(sorted[4][2]);
Your MultiDimensionalArray(iRows,iCols) function is defining the array contents as strings. When you try to add a number to an element in the array like: sorted[4][2] += 2 it is just concatenating to that string.
However the following should still work, even in that instance:
sorted[4][2] = parseInt(sorted[4][2])+parseInt(nbrMvt[i]);
Unless nbrMvt[i] is in an invalid format, causing parseInt() to return NaN. Which would make the sum also NaN.
Here is jsFiddle of working code similar to yours, with a small rewrite to your MultiDimensionalArray() function.
2 Comments
a[i][j] = ""; by a[i][j] = 0; in my MultiDimensionalArray function. Thank you :)parseInt("") is NaN. So your initial value breaks the sum of those two numbers.If you x+=4 you get NaN in x if it was null or undefined before.
It is good to fill thing you will += with number 0 first.
If you x+=4 you get "104" in x if it was string "10" before, not a number 10.
If you x+=y you get "104" in x even if x was previously number 10 but y is string "4".
It is good to explicitly cast to number (using +foo; that is unary plus, not the addition operator, the shortest way to force number coercion in Javascript) if you want to have number arithmetics.
sortedvariable. More than likely it's values are strings, causing the+=to be concatenation.MultiDimensionalArray(13,4). Are you using a framework?