如何在每次输入时停止替换数组中的元素?

时间:2017-05-11 14:23:27

标签: javascript arrays associative-array

我正在尝试编写输出类似以下内容的代码:

Dog 1 Name: Neo Toys: 3
Dog 2 Name: Henry Toys: 2

但是,我只会从最后的输入中得到结果。因此,如果我要输入上面的数据,我会用我的代码得到它。

Dog 1 Name: Henry Toys: 2

我如何制作它以便每次输入输入时都不会取代之前的输入?

var garrDog = [];

function start() {
    var valueToPush = {};
    var vName = '';
    var vToys = '';
    vName = prompt("Enter the dog's name (leave blank to stop)");
    vToys = prompt("Enter number of toys " + vName + " has (leave blank to stop)");
    valueToPush['dogName'] = vName;
    valueToPush['dogToys'] = vToys;
    while (vName.length > 0) {
        vName = prompt("Enter the dog's name (leave blank to stop)");
        if (vName.length > 0) {
            vToys = prompt("Enter number of toys " + vName + " has (leave blank to stop)");
            valueToPush['dogName'] = vName;
            valueToPush['dogToys'] = vToys;
        }
    }
    garrDog.push(valueToPush);
    listDogs();
}

function listDogs() {
    var i = 0;
    while (i < garrDog.length) {
        document.getElementById('output').innerHTML += ('Dog ' + (i+1) + ' Name: ' + garrDog[i].dogName + ' No. of toys: ' + garrDog[i].dogToys + '<br />');
        i++;
    }
}

1 个答案:

答案 0 :(得分:1)

您只执行一次push;它应该在循环中。此外,请确保在每次迭代中定义一个新对象,否则您将改变同一个对象,从而产生同一对象的重复数组。

以下是 start 功能的更正版本(其余功能保持原样):

function start() {
    garrDog = []; // Add this when you want to start from scratch each time
    vName = prompt("Enter the dog's name (leave blank to stop)");
    while (vName.length > 0) {
        var valueToPush = {};
        vToys = prompt("Enter number of toys " + vName + " has");
        valueToPush['dogName'] = vName;
        valueToPush['dogToys'] = vToys;
        garrDog.push(valueToPush);
        vName = prompt("Enter the dog's name (leave blank to stop)");
    }
    listDogs();
}

注意:我不会告诉用户他们可以为次要问题输入任何内容而停止。这将使一个条目不完整。只留下第一个问题的选项。

另外,请考虑将 garrDog 作为局部变量并将其传递给 listDogs 函数。这取决于您是否要维护列表并在每次调用 start 时扩展它。