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;

2 Answers 2

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] )
Sign up to request clarification or add additional context in comments.

2 Comments

Best practice is to include the radix too: parseInt(array1[i], 10)
another way is to use array1[i] * 1 + array2[i] * 1
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.