gpt4 book ai didi

javascript - 为 children 挑战 JavaScript。第六章什么是正确答案

转载 作者:行者123 更新时间:2023-11-30 08:26:48 25 4
gpt4 key购买 nike

在书:“JavaScript for kids”的第 6 章末尾,有一个创建随机字符串生成器的挑战,从 var alphabet = "abcdefghijklmnopqrstuvwxyz"中取出的字母;在书中,autor 专门要求使用我没有做到的 WHILE 循环。

然后我发现正确答案需要 FOR 循环并如下所示:

var alphabet = "abcdefghijklmnopqrstuvwxyz";
var randomString = "";
var stringLength = 6;

for (var i = 0; i < stringLength; i++) {
randomString += alphabet[Math.floor(Math.random() * alphabet.length)];
}

console.log(randomString);

我的问题:是否可以对 WHILE 循环做同样的事情?

最佳答案

每个for 循环都可以写成while 循环。通常,您的 for 循环描述符具有三个表达式:初始化、条件和某种增量。我们称它们为 abc

然后这个:

for (a; b; c) {
// ...
}

相当于:

a;
while (b) {
// ...
c;
}

注意:使用 let 时可能会有细微差别。

关于javascript - 为 children 挑战 JavaScript。第六章什么是正确答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44317458/

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