0

I need to make it so that rather than 1+1=11 my code will return 1+1=2

<!DOCTYPE html>
<html>
<body>

<script>
var  arr = [];                              

for (var i = 0; i < 7; i++) {              
  arr.push(prompt('Enter GTIN Digit ' + (i+1))); 
}

alert('Full GTIN: ' +  (arr [0]*3)+(+ arr [2]*3)+(arr [4]*3)+(arr [6]*3) + (arr [1])+(arr [3])+ (arr [5])             );  

</script>

</body>
</html>
Alex Newport
  • 61
  • 1
  • 1
  • 7

2 Answers2

0

Use parseInt()

parseInt(1)+parseInt(1)
Daniela
  • 234
  • 2
  • 13
0

Just one character you need to add: a + (unitary plus) before the prompt:

arr.push(+prompt('Enter GTIN Digit ' + (i+1)));

This will do the conversion.

Secondly, you need to avoid converting it back to string in your alert. Put the whole calculation between brackets or else the first string will make all the + act as string concatenation:

alert('Full GTIN: ' + (arr[0]*3+arr[2]*3+arr[4]*3+arr[6]*3+arr[1]+arr[3]+arr[5]));  

Or, using a reduce:

alert('Full GTIN: ' + arr.reduce((s, d, i) => s+(i%2?d:d*3), 0));

Convert the array

The unitary + solution seems the best to me, but if -- like you put in the title -- you really want to first build the array of strings and then convert the values, then use this statement:

arr = arr.map(Number);

Remarks

  • It is not user-friendly to ask repeated input via prompt. The user cannot interrupt that sequence or go back. Better is to use the input element with the number type.
  • You would need to validate the input. As soon as you have a NaN instead of a number, or the input consists of multiple digits instead of one, the calculation cannot work correctly, and so there is no use to finish the whole input cycle.
trincot
  • 317,000
  • 35
  • 244
  • 286