【问题标题】:Javascript If statementsJavascript If 语句
【发布时间】:2015-04-22 20:24:49
【问题描述】:

我们正在尝试使用 javascript 数组来打印生日(在实际日期)的人来存储信息。

我们有三个数组,一个用来存储日、月和人。

这就是我们现在所拥有的:

      <!DOCTYPE html>
    <html>
    <head>
    <link rel="stylesheet" type="text/css" href="css/main.css">
    <!--
        Look Into Connectors
        28 JANUARY 2015
        Assignment 1

        Author: 
        Date: 
        This is the index/ homepage of the website. It is the main page that a user should land on.

        Filename: webpage
        supporting files: 
    -->
         <title>A Look Into IT</title>
    </head>
    <meta charset="UTF-8">
    <meta name="description" content="This is a website that offers free information on IT">
    <body>

    <script type="text/javascript">
    <!--
    var bmonth = ["4","4","4","4", "4", "4", "4"]
    var bday = ["8","6","27","22", "23", "23", "9"]
    var person = ["Jesse", "john","billy" , " Buddy Dyer", "John Morgan", "Will Smith", "Jonny"]
    var currentTime = new Date()
    var month = currentTime.getMonth() + 1
    var day = currentTime.getDate()
    var year = currentTime.getFullYear()
    document.write(month + "/" + day + "/" + year)
    for(i=0; i<=6; i++){
      if (month = bmonth[i]){
        if(day = bday[i]){
            document.write(person[i])

              }
       }else{
      document.write("There are no birthdays today")
}
    }
    //-->
    </script>





        </body>
    </html>

这是输出: 2015 年 4 月 22 日杰西约翰比尔巴迪戴尔约翰摩根威尔史密斯乔尼

它只是打印所有的数组信息。

【问题讨论】:

  • 您确实需要更改问题标题。这不是关于 if 语句(动词),而是关于为什么你的代码没有按预期工作
  • 与其硬编码你的for 循环以在6 停止,你可能需要考虑添加更多的人/生日,这样你的代码就更灵活了。也许array 的某些属性可以,我不知道,count 它包含的项目数,因此您可以将其存储在变量中? ;) 也正如其他人指出的那样,研究分配与平等:= vs =====

标签: javascript html css if-statement


【解决方案1】:

而不是if (month = bmonth[i])if(day = bday[i]) 分别使用if (month == bmonth[i])if(day == bday[i])

您可能还想使用三重等于===,但这是另一个问题。

【讨论】:

  • for 语句的末尾添加break; 以阻止其计数也是一个好主意
【解决方案2】:

问题是您使用的是赋值运算符 = 而不是相等(有时称为相同)运算符 ==

但您可能仍然想知道为什么会得到输出:

JessejohnbillBuddyDyerJohnMorganWillSmithjonny

monthday 的值将被评估为 truthyness,并且数组中的所有值都评估为 true。这就是document.write(person[i]) 打印所有名称的原因。

另外,您确实需要使用分号。

【讨论】:

    猜你喜欢
    • 2021-09-11
    • 1970-01-01
    • 1970-01-01
    • 2015-05-01
    • 2016-06-21
    • 2012-02-11
    • 1970-01-01
    • 1970-01-01
    • 2011-01-03
    相关资源
    最近更新 更多