如何根据对话框的提示输入用户创建数组

时间:2019-01-20 14:10:35

标签: javascript arrays dialog

我正在努力选择和编写适当的代码来将用户输入从对话框提示循环到数组中。

我已经坚持了几天。我是编码的初学者,尤其是javascript。

alert("Welcome to my store!");
do{
    var nameArray;
    var name = prompt("Enter Product Name");
    var price = parseInt(prompt("Unit Price of Product in dollars: "));       
    var quantity = parseInt(prompt("Quanity of the product: "));
    var sum =price*quantity;
    userSelection = confirm("Do you want to purchase more?");
}
while(userSelection==true);
for(i=0;i>nameArray.length;i++){
    name[i]++;
    var totalSum = sum[i]++;
}
alert("You bought " +nameArray[]+ ". Your Total cost today is $"+totalSum+".");

我希望用户输入产品名称,价格和数量。我想创建一个警报,将其拉出并显示名称,然后计算总和。

2 个答案:

答案 0 :(得分:0)

我摆弄了一个小提琴并使其工作,主要是添加了一个篮子数组来跟踪用户添加的项目。

alert("Welcome to my store!");
var basket = [];
var totalSum = 0;
var items = "";
do{
    var name = prompt("Enter Product Name");
    var price = parseInt(prompt("Unit Price of Product in dollars: "));       
    var quantity = parseInt(prompt("Quanity of the product: "));
    var sum =price*quantity;
    basket.push( {name: name, price: price, quantity: quantity, sum: sum});
    userSelection = confirm("Do you want to purchase more?");
}
while(userSelection==true);
for(i=0;i<basket.length;i++){
    totalSum += basket[i].sum;
    items += basket[i].name+", ";
}
alert("You bought " +items+ ". Your Total cost today is $"+totalSum+".");

答案 1 :(得分:0)

尝试以下解决方案

alert('Welcome to my store!');

const items = [];

do {
    const name = prompt('Enter product name');
    const price = parseInt(prompt('Unit Price of Product in dollars'));
    const quantity = parseInt(prompt('Quanity of the product'));
    const sum = price * quantity;

    const item = {
        name: name,
        price: price,
        quantity: quantity,
        total: sum
    };

    items.push(item);
} while (confirm('Do you want to purchase more?'));

const totalCost = items.reduce((accumulator, currentValue) => accumulator += currentValue.total, 0);

alert(`You bought ${JSON.stringify(items, null, 4)} Your Total cost today is ${totalCost}`);
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
</body>
</html>

您可以阅读有关reduce here和JSON.stringify here

的内容。

令人鼓舞的是,这是一个伟大而美丽的世界