Skip to content
Advertisement

Fill array with prompt in JavaScript and use push method

I am learning arrays in JavaScript and I am using the foreach with the push method.

The following code is working as its supposed to:

    let numbers = [-1, -2, -3, 5, 6, 1]
    let pos = []
    let neg = []
    
    numbers.forEach(number => {
            if (number<0) {
            neg.push(number)
        } else {
            pos.push(number)
        }
        
        })
        
       document.write("Number of positive numbers are: "+pos + "<br>" + "<br>")
       document.write("Number of negative numbers are: "+neg)

But I want to replicate this with a prompt, instead of hard coding the values in the array. And end the prompt with a 0. The code I attempted is the following, but the variables pos and neg are never evaluated’, this is my code:

    let numbers = []
    let pos = []
    let neg = []

    let number = parseInt(prompt("Input nr"))
    document.write("Your input nr was: " + number + "<br>" + "<br>")
    
    while (number != 0) {

        number = parseInt(prompt("Input nr"))
        document.write("Your input nr was: " + number + "<br>" + "<br>")

        numbers.forEach(number => {
            if (number<0) {
            neg.push(number)
        } else {
            pos.push(number)
        }
        
        })

    }

    document.write("Number of positive numbers are: "+pos + "<br>" + "<br>")
    document.write("Number of negative numbers are: "+neg)

What have I done wrong in my code?

Advertisement

Answer

You need to push the number into numbers array

numbers.push(number)

let numbers = []
    let pos = []
    let neg = []

    let number = parseInt(prompt("Input nr"))
    numbers.push(number)
    document.write("Your input nr was: " + number + "<br>" + "<br>")
    while (number != 0) {

        number = parseInt(prompt("Input nr"))
        numbers.push(number)
        document.write("Your input nr was: " + number + "<br>" + "<br>")
    }
    numbers.forEach(number => {
            if (number<0) {
            neg.push(number)
        } else {
            pos.push(number)
        }
        
    })

    document.write("Number of positive numbers are: "+pos + "<br>" + "<br>")
    document.write("Number of negative numbers are: "+neg)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement