How to convert a string to a direct number from the prompt?

Asked

Viewed 188 times

1

I’m starting to learn JavaScript and I care about writing a code redundant/repetitive, has some more appropriate way of converting strings from prompt in numbers before inserting into array?

function getPoints() {
    var point
    var points = []
    
    for (var i = 0; i <= 2; i++) {
        point = prompt(`Pontuação obtida no exercício ${i+1}`)
        points[i] = Number(point)
    }
    return points
}
  • It did not work my answer Fabiana?

  • It did. The way you put it, using the push looks better, really. But my question was whether the conversion should be more summarized, without using a variable like that of the point to store the converted value before inserting it into the array.

  • There are no problems in creating variable, which will be used which is the case, the problem of your code was the lack of test and only enter numerical data

1 answer

-1


With parseInt (parses a string argument and returns an integer in the specified base) to convert the value and isNaN (determines whether the value is Nan or not) to check whether the parse happened successfully or returned NaN, also a change in the time to create the array, with push which automatically creates the position to insert the new value, example:

function getPoints() {
    let points = [];    
    for (var i = 0; i <= 2; i++) {
        //porde ser parseFloat se o numero tiver decimais Ex: 1.5
        let point = parseInt (
          prompt(`Pontuação obtida no exercício ${i+1}`)
        )        
        if (!isNaN(point)) {
          points.push(point);
        }
    }
    return points
}
console.log(getPoints());

only numerical values shall be inserted.

Browser other questions tagged

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