如何解决-每次都无法给出正确答案

时间:2019-01-30 14:50:08

标签: javascript

传递给函数的是生日:BirthDate = '02&22&1732';

它的称呼是:“他的美洲原住民图腾是:”“ + NATotem(BirthDate)+”“。\ n”;

var animal = '*** NOT SET ***';

var January = 1, February = 2, March     = 3, April   = 4,  May      = 5,  June     = 6;
var July    = 7, August   = 8, September = 9, October = 10, November = 11, December = 12;

function NATotem(A)
{
       var birthMonth = parseInt(A.substr(0,2).split("&"));
       var birthDY = parseInt(A.substr(3,2).split("&"));

       if (((birthMonth >= January)   && (birthDY >= 20)) || ((birthMonth <= February)  && (birthDY <= 18))) { animal = 'Otter'; } else
       if (((birthMonth >= February)  && (birthDY >= 19)) || ((birthMonth <= March)     && (birthDY <= 20))) { animal = 'Wolf'; } else
       if (((birthMonth >= March)     && (birthDY >= 21)) || ((birthMonth <= April)     && (birthDY <= 19))) { animal = 'Hawk'; } else
       if (((birthMonth >= April)     && (birthDY >= 20)) || ((birthMonth <= May)       && (birthDY <= 20))) { animal = 'Beaver'; } else
       if (((birthMonth >= May)       && (birthDY >= 21)) || ((birthMonth <= June)      && (birthDY <= 20))) { animal = 'Stag/Deer'; } else
       if (((birthMonth >= June)      && (birthDY >= 21)) || ((birthMonth <= July)      && (birthDY <= 21))) { animal = 'Woodpecker'; } else
       if (((birthMonth >= July)      && (birthDY >= 22)) || ((birthMonth <= August)    && (birthDY <= 22))) { animal = 'Salmon'; } else
       if (((birthMonth >= August)    && (birthDY >= 23)) || ((birthMonth <= September) && (birthDY <= 21))) { animal = 'Bear'; } else
       if (((birthMonth >= September) && (birthDY >= 22)) || ((birthMonth <= October)   && (birthDY <= 22))) { animal = 'Raven'; } else
       if (((birthMonth >= October)   && (birthDY >= 23)) || ((birthMonth <= November)  && (birthDY <= 22))) { animal = 'Snake'; } else
       if (((birthMonth >= November)  && (birthDY >= 23)) || ((birthMonth <= December)  && (birthDY <= 21))) { animal = 'Owl'; } else
       if (((birthMonth >= December)  && (birthDY >= 22)) || ((birthMonth <= January)   && (birthDY <= 19))) { animal = 'Goose'; }

       return animal;
}

它仅在部分时间内给出正确答案。我知道有一种bette方式,只是不知道如何使它起作用。

1 个答案:

答案 0 :(得分:1)

在几个月内使用等于。如果在第一个if语句上使用 <=一月,则大于一月且日期大于20的任何月份将匹配,之后的所有else语句将被忽略。

if (((birthMonth == January)   && (birthDY >= 20)) || ((birthMonth == February)  && (birthDY <= 18))) { animal = 'Otter'; } else