我对编程很陌生,并且尝试过编程if-否则的逻辑来创建数组等等。
我想使用一个点变量来决定变量在哪个点-区间内,然后为该区间制作带有函数的数组,然后从这个数组中返回一个随机函数。
例如,我有里程碑1000、2500等。如果userScorePoints超过2500个,我希望方法从包含该数字的函数的数组中返回一个随机函数,直到userScorePoints达到下一个里程碑,即5000。
我所写的代码的问题是,它只返回第一个假设的随机函数,所以我只能从数字1000中得到函数,尽管我应该从数字2500中得到函数,因为我现在的点数超过2603。
有人能帮帮我吗..?
这是我的密码
function getFunfact(userScorePoints) {
var array = new Array();
if (1000 <= userScorePoints < 2500) {
var funfact1000 = new Array();
funfact1000[0] = "funfacts about the number 1000";
funfact1000[1] = "...";
funfact1000[2] = "...";
funfact1000[3] = "...";
funfact1000[4] = "...";
funfact1000[5] = "...";
array = funfact1000;
} else if (2500 <= userScorePoints < 5000) {
var funfact2500 = new Array();
funfact2500[0] = "funfacts about the number 2500";
funfact2500[1] = "...";
funfact2500[2] = "...";
funfact2500[3] = "...";
funfact2500[4] = "...";
funfact2500[5] = "...";
array = funfact2500;
} else if (5000 <= userScorePoints < 10000) {
var funfact5000 = new Array();
funfact5000[0] = "funfacts about the number 5000";
funfact5000[1] = "...";
funfact5000[2] = "...";
funfact5000[3] = "...";
funfact5000[4] = "..."
funfact5000[5] = "...";
array = funfact5000;
} else if (10000 <= userScorePoints < 20000) {
var funfact10000 = new Array();
funfact10000[0] = "funfacts about the number 10.000";
funfact10000[1] = "...";
funfact10000[2] = "...";
funfact10000[3] = "...";
funfact10000[4] = "...";
funfact10000[5] = "...";
array = funfact10000;
} else if (20000 <= userScorePoints < 30000) {
var funfact20000 = new Array();
funfact20000[0] = "funfacts about the number 20.000";
funfact20000[1] = "...";
funfact20000[2] = "...";
funfact20000[3] = "...";
funfact20000[4] = "...";
funfact20000[5] = "...";
array = funfact20000;
} else if (30000 <= userScorePoints < 50000) {
//etc.
} else {}
return array[getRandom(6)]; //this method returns a random element, this one works.发布于 2013-08-30 08:32:46
不能像这样连锁关系比较。你必须写:
if (1000 <= userScorePoints && userScorePoints < 2500) {
...
}你所写的被解析,就好像你写了:
if ((1000 <= userScorePoints) < 2500) {
...
}括号中的比较计算结果为0或1,这通常小于2500。
发布于 2013-08-30 08:32:38
语法和你真正想要的是错的-
这是正确的语法-
if(5000 <= userScorePoints && userScorePoints < 10000)使用“&”进行多个逻辑比较。
我还将解释当您编写代码时解释器会理解什么,即-
if(5000 <= userScorePoints < 10000)基本上是做第一个比较5000 <= userScorePoints。结果将是一个true或false,在转换成一个数字时分别相当于1或0。
因此,在接下来的步骤中,如果上一次比较的结果是false,则比较0 < 10000或如果结果为true,则比较 1 < 10000。在这两种情况下,值都小于10000,这就是为什么条件总是为真的原因。
希望这能消除你的疑虑。编码愉快!
发布于 2013-08-30 08:32:52
编程不是数学。您的约定应以下列形式进行:
if (1000 <= userScorePoints && userScorePoints < 2500)https://stackoverflow.com/questions/18528330
复制相似问题