Home > Software engineering >  Working on a program that takes items to make a shopping list. I must store them as variables item1,
Working on a program that takes items to make a shopping list. I must store them as variables item1,

Time:12-08

Is there a way to reduce the number of prompts to one line of code, perhaps a prompt that allows for a multi-line input box when prompted in the format of a list? Any feedback is much appreciated.

let nameUser=prompt("What is your name?");//Request user to input their name

let item1=prompt("What is item 1 on your shopping list?");//Request user to input the first item on their shopping list
let item2=prompt("What is item 2 on your shopping list?");//Request user to input the second item on their shopping list
let item3=prompt("What is item 3 on your shopping list?");//Request user to input the third item on their shopping list

console.log(`${nameUser}'s shopping list:
${item1}
${item2}
${item3}
`);//Print users shopping list with template literals

I have tried to store the items as an array and split them but that doesn't help.

CodePudding user response:

You could use a forloop

let nameUser=prompt("What is your name?");//Request user to input their name

let items = [];

for(let i = 0; i < 3; i  ){
    items[i] = prompt(`What is item ${i 1} on your shopping list?`);
}


console.log(`${nameUser}'s shopping list: \n${items.join('\n')}`);

CodePudding user response:

You could do something like this:

let nameUser=prompt("What is your name?");
let obj = {}
for(let i=1;i<=3;i  ){
    obj[`item${i}`]=prompt(`What is item ${i} on your shopping list?`);
 }
 const {item1,item2,item3}=obj
 console.log(`${nameUser}'s shopping list:
 ${item1}
 ${item2}
 ${item3}
 `);
  • Related