我试图从给用户的提示中找到最大和最小数字。由于某种原因,似乎只有 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/