javascript - 如何将用户提示(输入)存储到数组中并检索它的最大值和最小值?

标签 javascript arrays split

我正在尝试将值输入到提示中,将值转换为整数,将值插入数组,然后从数组中检索最小值和最大值。我不知道是将用户输入转换为整数,还是将数组项转换为整数。我还需要一种将数组从一项拆分为输入大小的方法。例如,用户输入提示“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.minMath.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/

相关文章:

Javascript 返回错误

javascript - For 循环运行数组的长度,但显示一个元素数组。length 次

javascript - Angular2 OverlayComponent 不更新消息变量

javascript - 这两个请求之间的区别

PHP, in_array, 0 值

regex - 从电子表格中单元格的值解析字符串和对象

javascript - jquery - 分割和计算字符?

python - 无法在不转换为 ascii 的情况下拆分 unicode 字符串 - python 2.7

javascript - Ember.js setupController 仅触发一次

arrays - Perl循环遍历单个元素的数组哈希