0

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++.

1
  • C++ arrays are a lot more flexible than JavaScript arrays, so you should use an array method. Commented Nov 12, 2016 at 6:50

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

1 Comment

The array variable name should have a different name, because name is a name of a built in property in JavaScript. It will work on JSFiddle, but when the script is executed directly in a browser it will show name.push is not a function.
0

Use push to add new input to the array like this:

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

Comments

0

little bit of recursion

    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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.