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?)
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] += 2it is just concatenating to that string.However the following should still work, even in that instance:
Unless
nbrMvt[i]is in an invalid format, causingparseInt()to returnNaN. Which would make the sum alsoNaN.Here is jsFiddle of working code similar to yours, with a small rewrite to your
MultiDimensionalArray()function.