我想知道我的代码到底缺少什么或者为什么它不起作用
<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>
window.alert只是为了看看它是否被保存,我尝试在JS中使用c++风格,我知道我也许应该做push方法?但我不太确定,警报框中显示的所有内容均未定义,而且我不太确定为什么,任何帮助将不胜感激,谢谢。我不太确定 javascript 中允许什么以及不允许什么,我假设诸如递增之类的事情在 bot JS 和 C++ 中是相同的。
最佳答案
您需要有一个数组并推送元素,
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
关于javascript - 在 JavaScript 中将用户输入元素输入到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40560054/