gpt4 book ai didi

Javascript - 一切都超出范围

转载 作者:行者123 更新时间:2023-11-30 10:57:18 25 4
gpt4 key购买 nike

所以,我有这段代码:

<script>

//We'll pass you an array of two numbers.
//Return the sum of those two numbers plus the sum of all the numbers
//between them.
//The lowest number will not always come first.
function sumAll(arr) {

var number1 = arr[0];
var number2 = arr[1];

var lower_number;
var bigger_number;


if (number2 < number1) {
number2 = lower_number;
number1 = bigger_number;

} else {
number1 = lower_number;
number2 = bigger_number;

}
var i;

var something;

for (i = lower_number; i < bigger_number; i++) {

something = i + something;
console.log(i);

}
return something;
}
sumAll([1, 4]);
sumAll([4, 1]);

</script>

这行不通。当我尝试在控制台中查看结果(如 isomething)时,我只看到那里有 undefined

有什么建议吗?

此外,我如何才能实际验证函数的结果?我是 JS 的新手。

谢谢。

最佳答案

console.log(i)正在显示 undefined因为那是变量的值。这不是范围问题。

您从未将任何内容分配给 lower_number .所以当你做 i = lower_number ,你在做i = undefined ,这就是记录的内容。

实际上,你永远不应该进入循环,因为i < bigger_number总是会失败,因为 ibigger_number都是undefined , 和 undefined < undefined是假的。

原因是你之前的赋值是倒过来的。本节:

    if (number2 < number1) {
number2 = lower_number;
number1 = bigger_number;
} else {
number1 = lower_number;
number2 = bigger_number;
}

应该是:

    if (number2 < number1) {
lower_number = number2;
bigger_number = number1;
} else {
lower_number = number1;
bigger_number = number2;
}

分配的顺序总是destination = source; (这对大多数编程语言都很常见)。

您可以通过记录函数调用来验证函数的结果:

console.log(sumAll([1, 4]));

关于Javascript - 一切都超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59494781/

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