JavaScript循环中用unshift/push引发无限循环问题求解
解决无限循环问题并实现员工信息录入
你的推测完全正确:unshift()会在数组开头插入元素,导致数组长度每次循环都增加1,而你的循环条件是i <= employee.length,i每次只加1,数组长度同步增长,循环永远不会终止,陷入无限循环。另外你创建的new Array(allEmployeess)是指定长度但元素为空的数组,其实完全没必要,直接用空数组即可。
下面是用for和while循环实现的正确代码:
For循环实现
// 获取员工数量(可添加非数字输入的校验,这里先做基础实现) const employeeCount = Number(prompt("公司有多少名员工?")); const employees = []; for (let i = 0; i < employeeCount; i++) { const employee = { name: prompt(`请输入第${i + 1}名员工的姓名:`), salary: Number(prompt(`请输入第${i + 1}名员工的薪资:`)) }; // 用push往数组末尾添加元素,不影响循环次数 employees.push(employee); }
这里循环次数由employeeCount固定控制,不管数组长度怎么变,循环只会执行指定的次数,彻底避免无限循环。
While循环实现
const employeeCount = Number(prompt("公司有多少名员工?")); const employees = []; let currentIndex = 0; while (currentIndex < employeeCount) { const employee = { name: prompt(`请输入第${currentIndex + 1}名员工的姓名:`), salary: Number(prompt(`请输入第${currentIndex + 1}名员工的薪资:`)) }; employees.push(employee); // 每次循环后计数器加1,直到达到员工总数 currentIndex++; }
通过独立的计数器currentIndex控制循环终止条件,同样不受数组长度变化的影响。
额外说明
如果一定要使用unshift(),只需保证循环次数固定即可(结果是员工顺序倒转):
const employeeCount = Number(prompt("公司有多少名员工?")); const employees = []; for (let i = 0; i < employeeCount; i++) { const employee = { name: prompt(`请输入第${i + 1}名员工的姓名:`), salary: Number(prompt(`请输入第${i + 1}名员工的薪资:`)) }; employees.unshift(employee); }
另外你的原代码还有几个小问题:变量名allEmployeess多了一个s,contador变量未被使用,这些都可以优化掉。
内容的提问来源于stack exchange,提问作者Júlio César Amorim
相关产品推荐
相关产品推荐

