关于确定数组中存储的最大值的不同方法的一些问题(加上输出消息问题)



我有这个HTML/Javascript文档,它允许用户在文本字段中插入一个数字,单击按钮后,该数字存储在数组中,文本字段被清除,因此可以在数组中存储更多数字(用户想要的数量(。

用户还可以选择通过单击另一个按钮来确定数组中存储的最大数字,该按钮应打印一条消息,指出"数组中的最大数字是数字"。

现在,我找到了 3 个可能的选项来确定数组中存储的最多选项,但到目前为止我只能获得其中 2 个选项的工作,因为另一个选项返回 NaN。

在 3 个选项中,我的首选选项是返回 NaN 的选项,因为对我来说,它似乎没有其他 2 个那么复杂。我已经注释掉了 3 个选项中的每一个,以防人们想要测试它们。我还注释掉了输出消息(它没有打印我想要的内容(。

所以我的问题是:

  1. 如果我以前每次在数组中存储数字时都使用 parseInt,为什么 option1 会返回 NaN?

  2. 括号内的"数学"和"null"分别在选项 2 和选项 3 中表示或做什么?

  3. 为什么输出消息中缺少实际数字?(对不起,这个跑题了(

这是代码(我只用Internet Explorer测试(:

<html>
<head>
<script language="javascript" text="text/javascript">
var a=new Array();
var i=0;
function intoarray(){
    a[i]=parseInt(document.form1.valor.value);
    document.form1.valor.value="";
    i++;
}
function upper(){
    //option1 is my favorite because it's the shortest but results in the value of 'b' being NaN: 
    var b=Math.max(a);  
    //option2 works but I don't know what the 'Math' inside the parenthesis does:
    var b=Math.max.apply(Math, a);
    //option3 works but I don't know what the 'null' inside the parenthesis does::
    var b=Math.max.apply(null, a);
    //this is the output message I want, but it only prints "The highest value in the array is", leaving out the actual value
    alert("The highest number in the array is ", b); 
}
</script>
</head>
<body>
<form name="form1">
    <input type="text" id="valor">
    <input type="button" value="add" onClick="intoarray()">
    <input type="button" value="get highest" onClick="upper()">
</form>
</body>
</html>
1

(如果我以前每次在数组中存储数字时都使用parseInt,为什么选项1返回NaN

因为Math.max需要几个Number,而你正在传递一个数组。

2( 括号内的Mathnull分别代表选项2和选项3中的或做什么?

apply 采用一个 this 参数,该参数不在 Math.max 函数中使用,因此传递nullMath(可能还有其他任何内容(都可以。

我会使用传递Math的版本。原因是如果你提供 null ,则使用全局对象(在浏览器的情况下window(。传递Math更明确一些。

作为旁注,选项 2 和 3 都是查找数组最大值的标准方法。

3(为什么输出消息中缺少实际数字?(对不起,这个跑题了(

因为您需要将结果与消息字符串连接起来:

alert("The highest number in the array is " + b); 

相关内容

最新更新