我正在尝试编写一个 javascript 程序来显示用户输入的 10 个数字中最大的一个。这是我到目前为止所拥有的,但没有用。
<html>
<head></head>
<body>
<script type="text/javascript">
var counter=1;
var number= new Array;
number.length=9;
var largest=0;
while (counter <= 10) {
number=window.prompt("Enter Numbers 1-10 Number:"+counter+".");
number[counter]= parseInt(number);
counter++;
}
largest=Math.max.apply(Array);
document.writeln("<h1>Largest number is " +largest+ "</h1>");
</script>
</body>
</html>
最佳答案
您只是缺少 Function.prototype.apply
的预期 thisArg
.
Syntax , 正如 MDN 所描述的那样
fun.apply(thisArg[, argsArray])
如这个简单的例子所示
Math.max.apply (null,[5,4,3,7,9,]) //9
^^^^
为了简单起见,示例中使用了 null
,因为 Math 不需要特定的上下文
您要做的是将数组 number
传递给 Math.max
,然后就是 thisArg
(虽然你似乎把它误认为是 Array
) 这将导致 两种方式 在 Math.max
中以零参数调用,根据 §15.8.2.11
Given zero or more arguments, calls ToNumber on each of the arguments and returns the largest of the resulting values.
- If no arguments are given, the result is −∞.
关于javascript - 使用 JavaScript 查找数组中的最大元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19322775/