You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript新手求助:修复矩形输入验证的while循环代码

修复矩形宽高输入验证函数的问题

作为JavaScript初学者,你要实现getWidth()和getLength()函数来获取合法的矩形宽高输入,下面针对你给出的两个方案的问题逐一修正:

方案1的问题与修复

原代码核心错误:

  • while循环条件逻辑颠倒:!isNaN(width)应该是isNaN(width),我们需要在输入是无效数字(NaN)、非正数时重新提示
  • 重新输入时未用parseFloat()转换,导致width变成字符串,typeof width !== 'number'始终为真,陷入死循环

修正后的方案1代码:

const getWidth = function () {
  let width;
  width = parseFloat(prompt('Enter the width of your rectangle '));
  // 输入无效(非数字/非正数)时持续提示
  while (isNaN(width) || width <= 0) {
    width = parseFloat(prompt('Enter a valid value (positive number only)'));
  }
  return width;
};

let newWidth = getWidth();
console.log(newWidth);

方案2的问题与修复

原代码核心错误:

  • do-while循环条件完全错误:typeof width==='string'永远不成立,因为parseFloat()返回的始终是number类型(哪怕是NaN);条件逻辑混乱导致循环无法正常触发
  • if判断逻辑颠倒:width <= 0是非法值,不该返回;!isNaN(width)和前面的条件冲突,导致有效输入无法正确返回

修正后的方案2代码(do-while更适合至少执行一次输入的场景):

const getWidth = function () {
  let width;
  do {
    width = parseFloat(prompt('Enter the width of your rectangle '));
    // 输入为有效正数时直接返回
    if (!isNaN(width) && width > 0) {
      return width;
    }
    alert('Invalid input! Please enter a positive number.');
  } while (true); // 持续循环直到输入有效
};

let newWidth = getWidth();
console.log(newWidth);

也可以把循环条件明确化,不用无限循环:

const getWidth = function () {
  let width;
  do {
    width = parseFloat(prompt('Enter the width of your rectangle '));
  // 输入无效(非数字/非正数)时继续循环
  } while (isNaN(width) || width <= 0);
  return width;
};

let newWidth = getWidth();
console.log(newWidth);

方案2原while循环失效的原因:parseFloat()返回值永远是number类型,typeof width==='string'条件始终为假,再加上其他条件逻辑错误,导致循环无法持续执行。


内容的提问来源于stack exchange,提问作者MichaelSTL

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 02:21:17