gpt4 book ai didi

javascript - 为什么我的程序无论用户输入如何总是打印第一个条件?

转载 作者:行者123 更新时间:2023-11-30 07:14:41 26 4
gpt4 key购买 nike

我正在编写一个程序,该程序在执行时应根据用户输入选择两个数组之一,然后从该数组向控制台打印一个随机变量。

当程序运行时,当我在shell提示中输入arrayOneSelect时,它将正确打印出no。但是,当我在外壳程序提示符中输入yes时,不会打印arrayTwoSelect。而是,程序选择输入no的条件并打印arrayOneSelect。当我输入其他内容时,也会发生相同的情况-程序仍选择第一个条件并打印arrayOneSelect

谁能告诉我为什么会这样吗?

var arrayOne= ["Hello", "Goodbye", "How are you?", "What's happening?", "See you later"];
var arrayTwo= ["Dog", "Cat", "Duck", "Goose"];
var arrayOneSelect= arrayOne[Math.floor(Math.random() * (arrayOne.length))];
var arrayTwoSelect= arrayTwo[Math.floor(Math.random() * (arrayTwo.length))];
var select= prompt("Ready for an adventure?");
if(select= "no") {
console.log(arrayOneSelect);

}
else if(select= "yes") {
console.log(arrayTwoSelect);

}
else {
console.log("Try again!");

}

最佳答案

您的if语句分配给变量,而不检查它。

你想做的if(select == 'no')

当您执行if(select = 'no')时,您将'no'分配给select var,并且在javascript中不是nullundefinedfalse的任何内容都是真实的(意味着它被解释为true

虽然在这种情况下==很好,但是最佳实践是使用===参见Equality comparisons and sameness

关于javascript - 为什么我的程序无论用户输入如何总是打印第一个条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30552232/

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