簡體   English   中英

正在編寫一個程序,該程序將物品制作成購物清單。 我必須將它們分別存儲為變量 item1、item2、item3 和 output 每個項目

[英]Working on a program that takes items to make a shopping list. I must store them as variables item1,item2,item3 and output each item separately

有沒有辦法把提示數量減少到一行代碼,也許是一個列表格式提示時允許多行輸入框的提示? 非常感謝任何反饋。

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

我試圖將項目存儲為數組並將它們拆分,但這沒有幫助。

你可以使用 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')}`);

你可以這樣做:

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}
 `);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM