在我的“if / else”中声明我的“其他”声明不起作用 [英] In my "if/else" statement my "else" statement isn't working

查看:157
本文介绍了在我的“if / else”中声明我的“其他”声明不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对编码非常陌生(使用codeacademy学习Javascript),我需要一点帮助,我正在研究这个迷你项目。我试图让计算机随机选择两个不同阵列中的男孩名字或女孩名字。我使用if / else语句让计算机在boynames数组或girlnames数组之间进行选择。出于某种原因,当我运行代码时,它只执行girlname循环(if部分),但不运行boyname循环(else部分。)任何关于如何让它执行if / else的建议功能正常?代码在下面,请提前感谢!

I am very new to coding (using codeacademy to learn Javascript) and I need a little help with this mini project I'm working on. I am trying to make the computer randomly choose either a boy name or girl name from two different arrays. I used an if/else statement to make the computer choose between the boynames array or the girlnames array. For some reason when I run the code it only executes the girlname loop (the "if"part) but does not run the boyname loop (the "else" part.) Any advice on how I can get it to execute the if/else function properly? The code is below, thank you in advance!

<script>

var lastname = prompt("What is your last name?");
var useranswer = prompt("Are you having a baby girl or boy");

var girlnames = ["Lana", "Michelle", "Rebecca", "Angelina", "Carrie", "Natalia",
    "Rosie", "Heather", "Monica", "Lindsay"]

var random = girlnames[Math.floor(Math.random() * girlnames.length)];

var boynames = ["Justin", "Ryan", "Adler", "Darren", "Michael", "Kyle", "Taylor",
    "Winston", "Jacob", "Samuel", "Oliver"]

var rand = boynames[Math.floor(Math.random() * boynames.length)];


if (useranswer = "girl") {
    for (var i = 0; i <= girlnames.length; i++) {
        confirm("Your future daughter's name is" + " " + random + " " + lastname);
    }
} else {
    for (var j = 0; j <= boynames.length; j++) {
        confirm("Your future son's name is" + " " + rand + " " + lastname);
    }
}      

</script>


推荐答案

这是因为你使用了 = 而不是 ==

It is because you used = instead of ==.

单个等号用于赋值和两个等于比较

A single equal sign is used for assignment and two equals are a comparison.

这篇关于在我的“if / else”中声明我的“其他”声明不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆