gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 19:27:41 24 4
gpt4 key购买 nike

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

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

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

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

所以我的问题是:

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

  2. 选项2和选项3中括号内的“Math”和“null”分别代表或做什么?

  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) Why is option1 returning a NaN, if I have previously used a parseInt every time a number is stored in the array?

因为Math.max需要几个 Number 并传递给它一个数组。

2) What do the Math and null inside the parenthesis represent or do in option2 and option3 respectively?

apply接受一个 this 参数,该参数未在 Math.max 函数内部使用,因此传递 nullMath (或者可能是其他任何东西)有效。

我会使用传递数学的版本。原因是,如果您提供 null,则会使用全局对象(在浏览器中为 window)。通过数学有点更明确。

作为旁注,选项 2 和 3 都是 pretty standard ways查找数组的最大值。

3) Why is the actual number missing in the output message? (sorry for this one being off-topic)

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

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

关于javascript - 关于确定数组中存储的最高值的不同方法的一些问题(加上输出消息问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27511246/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com