Do not correctly sum data coming from window.prompt

Asked

Viewed 40 times

0

I am making a code in javascript and receiving data from the user and recording in a vector, but when adding it returns all the data typed

for(var contar = 0; contar < quantidade; contar++){

    var vei = window.prompt('Número de Veículos:')
    veiculos.push(vei)  
}
var total = veiculos.length
var soma = 0

for(var pos in veiculos){
    soma += veiculos[pos]
}
res.innerHTML += `Soma: ${soma}</br>`

1 answer

0


You need to convert the result of window.prompt for an integer, the result comes as a string.

Do partInt() to be able to perform the conversion, soon after the sum works correctly.

var veiculos = []
var quantidade = 5
for(var contar = 0; contar < quantidade; contar++){
    var vei = parseInt(window.prompt('Número de Veículos:'))
    veiculos.push(vei)  
}
var total = veiculos.length
var soma = 0

for(var pos in veiculos){
    soma += veiculos[pos]
}
console.log(`Soma: ${soma}`)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.