Entering user inputed elements into an array in JavaScript

时间:2016-11-12 06:03:27

标签: javascript arrays

I was wondering what exactly my code is missing or why it wont work

    <script>
        var index = 0;
        var  name = [];
        while (true)
        {        
        var add = window.confirm("Would you like to enter an employee");
        if (add === true)
        {
        name[index] = prompt("Please enter and employee name");
        ++index;
        }
        else
            break;
        }
        window.alert(name[0]);

    </script>

The window.alert is just to see if it gets saved, Im trying to use c++ style in JS, I know I maybe should be doing the push method? But Im not really sure, all it says in the alert box is undefined, and Im not really sure why, any help would be greatly appreciated, thank you. And Im not really sure what is, and what isnt allowed in javascript, I assumed things like incrementing are the same in bot JS and C++.

3 个答案:

答案 0 :(得分:1)

You need to have an array and push the elements,

var index = 0;
var names = [];
while (true) {
  var add = window.confirm("Would you like to enter an employee");
  if (add === true) {
    var newname = prompt("Please enter and employee name");
    names.push(newname);
    ++index;
  } else
    break;
}
window.alert(names);

DEMO

答案 1 :(得分:0)

使用push向数组添加新输入,如下所示:

&#13;
&#13;
var index = 0, employee;
        var  nameArr = [];
        while (true)
        {        
        var add = window.confirm("Would you like to enter an employee");
        if (add === true)
        {
        employee = prompt("Please enter and employee name");
        nameArr.push(employee);
        ++index;
        }
        else
            break;
        }
        window.alert(nameArr[0]);
        console.log(nameArr);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

一点点递归

    function addEmployee(arr) {
        let name = arr ? arr : [];
        let yes = confirm("Would you like to enter an employee");
        if (yes) {
        let employee = prompt("Please enter and employee name");
            name.push(employee);
            addEmployee(name);
        } else {
            alert(name);
        }
    };
    addEmployee();