javascript - 为什么我的 JavaScript 中没有显示最大数量?

标签 javascript math

我试图从给用户的提示中找到最大和最小数字。由于某种原因,似乎只有 Math.min 起作用,而 Math.max 不起作用。这是为什么?

var userNum = parseInt(window.prompt("Enter five numbers separated by commas"), 10);

window.console.log("The lowest number is: " + Math.min(userNum));

window.console.log("The highest number is: " + Math.max(userNum));
//HIGHEST DOES NOT SEEM TO WORK

最佳答案

您正在解析一个字符串,其中包含一系列逗号分隔的数字,但 parseInt 不会返回您想要的内容,而是仅返回该序列中的第一个数字。

您想要达到的结果:

var userNum = prompt("Enter five numbers separated by commas").split(',')
// prompt returns a string, you can make an array splitting by commas
// https://www.w3schools.com/jsref/jsref_split.asp

window.console.log("The lowest number is: " + Math.min( ...userNum ));
// spread the array into min() and max() with ... operator
// https://codeburst.io/javascript-es6-the-spread-syntax-f5c35525f754

window.console.log("The highest number is: " + Math.max( ...userNum ));

关于javascript - 为什么我的 JavaScript 中没有显示最大数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55563361/

相关文章:

javascript - 位置 : -webkit-sticky not working on safari

javascript - 让变量继承现有原型(prototype)的方法?

java - 将 List<Integer> 分成 5 个最小值周围的 5 个 block 列表的好方法

arrays - 简单的面试问题变得更难了 : given numbers 1. .100,找到恰好 k 丢失的缺失数字

c - 简单加密 - C 中的哈希总和

python - 如何在 python 中计算正态分布百分比点函数

python - 在Python中处理大二项式的求和

javascript - 如何捕获正则表达式 .match() 的剩余部分?

php - 访问多个复选框的值

javascript - 如何向全局数组添加异步信息?