0

I'm trying to make operations with numbers that are stored in arrays, unfortunately they seem to be considered as "text" rather than numbers, so when I do like array1[i] + array2[i], instead of doing 2+3=5 I would get 2+3=23 ...

The values of these arrays come from fields (html)

No idea how to deal with that ;D Thanks for your help

If you wanna look at my code, here's what it looks like :

        var polynome = [];
        for (var i=0; i<=degree; ++i) {
            polynome[i] = document.getElementById(i).value;
        }
        var a = document.getElementById("a").value;

        var tempArray = [];
        var quotient = [];

        quotient[degree+1] = 0;

        for (var i=degree; i>=0; --i) {
            tempArray[i] = a * quotient[i+1];
            quotient[i] = polynome[i] + tempArray[i];
        }

        document.getElementById("result").innerHTML = polynome + "<br>" + tempArray + "<br>" + quotient;
Zizi
  • 11
  • 2

2 Answers2

2

array1[i] contains string and not int so when you are trying both elements with + operator it is concatenating both the values rather of adding them

you need to cast both elements in arrays to integer

try this

parseInt( array1[i] ) + parseInt( array2[i] )
zzlalani
  • 22,960
  • 16
  • 44
  • 73
0

The + punctuator is overloaded an can mean addition, concatenation and conversion to number. To ensure it's interpreted as addition, the operands must be numbers. There are a number of methods to convert strings to numbers, so given:

var a = '2';
var b = '3';

the unary + operator will convert integers and floats, but it's a bit obscure:

+a + +b 

parseInt will convert to integers:

parseInt(a, 10) + parseInt(b, 10);

parseFloat will convert integers and floats:

parseFloat(a) + parseFloat(b);

The Number constructor called as a function will convert integers and floats and is semantic:

Number(a) + Number(b);

Finally there is the unary - operator, but it's rarely used since subtraction (like multiplication and division) converts the operands to numbers anyway and it reverses the sign, so to add do:

a - -b
RobG
  • 142,382
  • 31
  • 172
  • 209