gpt4 book ai didi

javascript - 为什么这个 for 循环不起作用?

转载 作者:行者123 更新时间:2023-11-28 13:16:33 25 4
gpt4 key购买 nike

两者之间的确切区别是什么:

<p id="test"></p>

<script>

function findMax() {
var i;
var max = -Infinity;
for(i=0;i<arguments.length;i++) {
if(arguments[i] > max) {
max = arguments[i];
}
}
return max;
}

document.getElementById('test').innerHTML = findMax(32, 133, 83, 163);

</script>

和:

<p id="test"></p>

<script>

function findMax() {
var i = 0;
var max = -Infinity;
for(; i < arguments.length ; i++) {
if(arguments[i] > max) {
max = arguments[i];
}
}
return max;
}

document.getElementById('test').innerHTML = findMax(32, 133, 83, 163);

</script>

也许我错过了一些类(class),但第一个类(class)输出 163,这是应该的,而第二个类(class)输出 0。控制台显示

SyntaxError: return not in function

return max;

为什么第二个返回最低值,而第一个返回最高值?

最佳答案

while the second one outputs 0.

您没有将i初始化为0

这意味着 i 未定义,并且 undefined + 1NaN

SyntaxError: return not in function

for 循环后漏掉了大括号,因此 return 语句超出了函数定义

function findMax() {
var i;
var max = -Infinity;
for(i = 0; i < arguments.length ; i++)
{//this was missed
if(arguments[i] > max)
{
max = arguments[i];
}
}
return max;
}

关于javascript - 为什么这个 for 循环不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37414809/

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