如何使用Prompt、FOR/do/while循环结合Math对象查找最大数值
实现方案
你可以通过for循环动态接收输入,不需要提前定义存储对象,两种更简洁的实现方式如下:
方式1:循环过程中直接比对,无需存储所有输入值
每次拿到输入值直接和当前最大值比对,不需要额外的存储空间,代码最精简:
// 自定义需要输入的数字数量 const inputCount = 4; let maxValue = -Infinity; for (let i = 1; i <= inputCount; i++) { const currentNum = parseInt(prompt(`Enter your number${i}`)); // 过滤非有效数字的输入 if (!isNaN(currentNum)) { maxValue = Math.max(maxValue, currentNum); } } console.log('最大数值为:', maxValue);
方式2:存入数组后统一计算最大值
如果后续还需要使用所有输入的数字,可以先存到数组中,再通过展开运算符传给Math.max:
// 自定义需要输入的数字数量 const inputCount = 4; const numList = []; for (let i = 1; i <= inputCount; i++) { const currentNum = parseInt(prompt(`Enter your number${i}`)); // 过滤非有效数字的输入 if (!isNaN(currentNum)) { numList.push(currentNum); } } console.log('最大数值为:', Math.max(...numList));
两种方案都支持灵活调整输入的数字数量,只要修改inputCount的数值即可,不需要手动新增存储属性。
内容的提问来源于stack exchange,提问作者Aliv
相关产品推荐
相关产品推荐

