Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

198
Visualizações
I'm trying to use a while loop to take user input and insert into an array Javascript

So im trying to take userResponse from prompt, convert it into an integer, then take that response and add it to my total. As long as my total is under 35 it should keep looping. Once the total userResponse has reached 35, the userResponse should be pushed into shoppingCart array and then the loop should break and an alert appear that they have reached the threshhold of 35. (btw sorry I'm new to stackoverflow, excuse my newbieness).

//==== VARIABLES ========
let shoppingCart = [];
let shippingThreshhold = 35; 
let userResponse;
let total;

//==== LOGIC ========

//CHECK FOR ITEMS UNTIL THRESHOLD IS MET.
while (total < shippingThreshhold){
  
  //GET ITEM COST FROM USER
  let userResponse = prompt("What is the value of the item you have selected?");

  //CONVERT USER INPUT TO A NUMBER
  userResponse.parseInt();

  //ADD ITEM COST TO RUNNING TOTAL VARIABLE
  let total = shippingThreshhold - userResponse

  //PUSH ITEM COST TO CART ARRAY
  userResponse.concat(shoppingCart);
}

//SEND POPUP MESSAGE TO USER
alert("Your shipping for this order will be free!");

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

There are a few issues with your code:

  1. You need to initialize total
  2. You don't add item cost to total properly
  3. You don't parse the userResponse using parseInt properly
  4. You don't push userResponse to the shoppingCart properly
  5. There's no reason to declare userResponse globally.

Some improvements you could also make:

  1. No need to store the total, as you can use the shoppingCart to calculate that (but I've kept total to keep it simpler).
  2. Show the user their cart both as they go and at the end.
  3. Format the shippingThreshold constant using a conventional naming format for constants (all caps separated by underscore).
  4. Use const instead of let when possible, to avoid unintentionally overwriting variable values.
  5. Handle edge cases.

//==== VARIABLES ========
const shoppingCart = [];
const SHIPPING_THRESHOLD = 35;
let total = 0;

//==== LOGIC ========

//CHECK FOR ITEMS UNTIL THRESHOLD IS MET.
while (total < SHIPPING_THRESHOLD) {
  
  //GET ITEM COST FROM USER
  const userResponse = prompt(`Your cart: ${shoppingCart.length ? shoppingCart : 'empty' }. What is the value of the item you have selected?`);
  
  if (userResponse === null) {
    break
  } else {
    //CONVERT USER INPUT TO A NUMBER
    const itemCost = parseInt(userResponse);
    
    if (Number.isNaN(itemCost)) {
      alert(`"${userResponse}" is not a number please try again or press cancel to exit.`)
    } else {
      // ADD TO TOTAL
      total += itemCost

      //PUSH ITEM COST TO CART ARRAY
      shoppingCart.push(itemCost);
    }
  }
}

//SEND POPUP MESSAGE TO USER
if (total >= SHIPPING_THRESHOLD) {
  alert(`Your shipping for this order will be free! Your cart: ${shoppingCart}`);
} else {
  alert("Thanks for visiting!")
}

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda