我正在尝试将值输入到提示中,将值转换为整数,将值插入数组,然后从数组中检索最小值和最大值。我不知道是将用户输入转换为整数,还是将数组项转换为整数。我还需要一种将数组从一项拆分为输入大小的方法。例如,用户输入提示“1 2 10 40”,然后会收到警告,最小值为 1,最大值为 40。数组长度应为 4。以下是我篡改的代码:
var numInput = prompt("Enter a series of numbers with spaces in between each:");
var numArray = [];
numArray.push(numInput);
numInput.split(" ");
alert(Math.min(numArray));
alert(Math.max(numArray));
最佳答案
您需要将.split
的结果分配给数组变量。
Math.min
和 Math.max
期望数字位于单独的参数中,而不是数组中。您可以使用 apply
将数组分散到参数中。
var numInput = prompt("Enter a series of numbers with spaces in between each:");
var numArray = numInput.split(" ");
alert(Math.min.apply(null, numArray));
alert(Math.max.apply(null, numArray));
关于javascript - 如何将用户提示(输入)存储到数组中并检索它的最大值和最小值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31197481/