如果javascript中的if条件不起作用,怎么办

时间:2019-08-05 06:34:20

标签: javascript

该函数中,除第一个IF之外,所有条件都得到满足

我以前曾尝试将每个赌注放在一个单独的括号中,并且即使使用切换下注且切换中没有下注也没有反应。

function my_information() {
  var information_statuss = ["the name dosnt import,please try again", "the family dosnt import,please try again", "the age dosnt import,please try again"];
  var status;
  var name = prompt("please import your name");
  var family = prompt("please import your family");
  var age = prompt("please import your age");
  (function() {
    if (name == null && family == null && age == null) {
      var i;
      for (i = 0; i < information_statuss.length; i++) {
        alert(information_statuss[i]);
      }
    } else if (name == null || name == "") {
      status = information_statuss[0];
      alert(information_statuss[0]);
    } else if (family == null || family == "") {
      status = information_statuss[1];
      alert(information_statuss[1]);
    } else if (age == null || age == "") {
      status = information_statuss[2];
      alert(information_statuss[2]);
    } else {
      status = null;
      var person = new object_constructor(name, family, age);
      console.log(person);
      var people = [];
      people.push(person);
      var inf = document.getElementById('information');
      var info;
      for (I in people) {
        info +=
          "NAME : " + people[I].name + "<br>" +
          "FAMILY : " + people[I].family + "<br>" +
          "AGE : " + people[I].age + "<br>" + "<hr>";
      }

      inf.innerHTML += info;
    }
  })();
}

my_information()

满足条件后,应该在屏幕上向用户显示三个警报(单击每个警报的“确定”按钮之后)。

3 个答案:

答案 0 :(得分:3)

只需在以下条件下使用

if (!name && !family && !age)

''null是伪造的值。 https://developer.mozilla.org/en-US/docs/Glossary/Falsy

答案 1 :(得分:0)

这将帮助您并使您的代码更简单。

if (!name && !family && !age) {
    var i;
    for (i = 0; i < information_statuss.length; i++) {
        alert(information_statuss[i]);
    }
} else if (!name) {
    status = information_statuss[0];
    alert(information_statuss[0]);
} else if (!family) {
    status = information_statuss[1];
    alert(information_statuss[1]);
} else if (!age) {
    status = information_statuss[2];
    alert(information_statuss[2]);
} else {
    status = null;
    var person = new object_constructor(name, family, age);
    console.log(person);
    var people = [];
    people.push(person);
    var inf = document.getElementById('information');
    var info;
    for (I in people) {
        info +=
            "NAME : " + people[I].name + "<br>" +
            "FAMILY : " + people[I].family + "<br>" +
            "AGE : " + people[I].age + "<br>" + "<hr>";
    }

    inf.innerHTML += info;
}

答案 2 :(得分:-1)

您正在检查name == null,但是当用户未填写任何名称时,name参数将变为空白字符串,不为null,并且对于家庭和年龄也相同。所以用这个条件

if (name != "" && family != "" && age != "")