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.