gpt4 book ai didi

javascript - 查找变量 - Javascript

转载 作者:行者123 更新时间:2023-12-02 17:01:09 25 4
gpt4 key购买 nike

我是一名 Javascript 初学者,我在获得下面问题的一部分的答案时遇到了一些困难。

Trace the following JavaScript code, and write the final values of the variables (x, y, z, w). Show your working.

function hot(a, b, c) {
if (a == b) {
return (c + b);
}
else if (a > b) {
return (c + c);
}
else {
return cold(b);
}
}


function cold(a) {
var ans = a;
for (var i = 0; i < 3; i++) {
ans = ans + a;
}
return ans;
}


var x = 10;
var y = 3;
x = x + 8;
var z = hot(x, y, x);
var w = 2;
w = hot(w, z, x);
y = y + “5”;

我算出x = 18y = "35"z = 36
W 是什么让我感到困惑我知道它= 144,但我只是不知道如何。
如果有人可以解释一下当它运行冷函数时会发生什么。

最佳答案

冷函数运行时需要 a ,将其分配给变量 ans然后启动 for while 0 <= i < 3 运行的循环,添加aans每次。

所以如果循环变量 i从 0 开始,运行一次 ( ans + a ),然后再次运行 i=1 ( ans + a + a ) 和 i=2 (ans + a + a + a)。所以函数返回4a

cold(2)

var ans = 2;

i = 0, 0 < 3, therefore ans = 2 + 2
i = 1, 1 < 3, therefore ans = 2 + 2 + 2
i = 2, 2 < 3, therefore ans = 2 + 2 + 2 + 2
i = 3, 3 = 3, therefore loop ends

2 + 2 + 2 + 2 = 4(2)

关于javascript - 查找变量 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25710242/

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