gpt4 book ai didi

javascript if else逻辑不起作用

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:53:38 24 4
gpt4 key购买 nike

我是编程新手,曾尝试编写 if-else 逻辑来创建数组等。

我想使用一个点变量来决定变量落在哪个点区间内,然后用该区间的函数创建数组并从该数组返回一个随机函数。

例如,我有里程碑 1000、2500 等。如果 userScorePoints 超过 2500,我希望该方法从包含关于该数字的 funfact 的数组中返回一个随机 funfact,直到 userScorePoints 达到下一个里程碑,即 5000。

我写的代码的问题是它只从第一个 if 返回一个随机的 funfact,所以我只从数字 1000 中得到 funfact,尽管我应该从数字 2500 中得到 funfact,因为我现在的分数是超过 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.

最佳答案

你不能像那样链接关系比较。你必须写:

if (1000 <= userScorePoints && userScorePoints < 2500) {
...
}

你写的内容被解析为就像你写的一样:

if ((1000 <= userScorePoints) < 2500) {
...
}

括号中的比较结果为 0 或 1,总是小于 2500。

关于javascript if else逻辑不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18528330/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com