为什么数组不接受推送的变量?

4

我想创建一个包含6个(半)随机小知识类别ID号的数组,这些ID号是从jService API获取的。我的代码已经设置好了迭代,如果该ID号尚未包含在空的categories数组中,则将新的随机类别ID号推入其中。

每次迭代后,我都使用console.log记录变量categories以供参考。看起来ID号被推入了数组中,但是在每次迭代后都被替换了,留下5个空的数组项?我尝试使用category[i]=randomCatId来创建一个嵌套迭代的category索引号,并将ID号添加到其中,但无法使其正常工作。难道push方法不能正常工作吗?非常感谢任何帮助解释为什么会发生这种情况。谢谢。

let categories = [];

async function getCategoryIds() {
    // save random number from one to 18000 to randomInt
    // randomInt will be used as the "offset" parameter to get a random sequence of categories
    let randomInt = Math.floor((Math.random() * 18000) + 1);
    let res = await axios.get(`http://jservice.io/api/categories?count=100&offset=${randomInt}`);
    // create a loop to iterate until the categories array contains 6 items
    for (i=0;categories.length=6;i++){
        // pull random ID number from the 100 categories pulled from API
        let i= Math.floor((Math.random() * 100) + 1);
        let randomCatId= res.data[i].id;
        console.log("randomCatId =", randomCatId);
        console.log(!categories.includes("randomCatId"));
        // if categories array does not include the randomCatId, add it to the categories array
        if (!categories.includes("randomCatId")){
            categories.push(randomCatId);
        }
        console.log("categories =", categories)
        // categories.push(randomCatId);
    }
}
<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Jeopardy</title>
  <link href="https://fonts.googleapis.com/css?family=Copse&display=swap"
        rel="stylesheet">
  <link rel="stylesheet" href="jeopardy.css">
</head>
<body>

<script src="https://unpkg.com/jquery"></script>
<script src="https://unpkg.com/axios/dist/axios.js"></script>
<script src="https://unpkg.com/lodash"></script>
<script src="jeopardy.js"></script>

</body>
</html>


1
你需要检查 categories.length === 6,否则这个循环将永远运行。 - Edward Romero
1
我不确定这是否是问题的原因,但您的循环头部很奇怪。for (i=0;categories.length=6;i++) - 中间子句应该是 categories.length < 6,不是吗?实际上,我认为这应该是一个 while 循环:while(categories.length < 6) - Robin Zigmond
https://dev59.com/T13Ua4cB1Zd3GeqP-j1r - Roko C. Buljan
@RobinZigmond 是的!这就是“奇怪”的循环头的问题所在。尝试了while循环,也行得通。 - personwholikestocode
1个回答

3
你的for循环没有正确检查如何结束循环,因此它将一直运行。
将你的for循环更改为:
for (i=0;categories.length<=6;i++)

感谢您找到这个问题!我已经进行了更正,但是现在循环似乎根本没有发生?在浏览器控制台调用函数后,似乎类别数组仍然为空。 - personwholikestocode
1
@Bolmstead 抱歉,已修复检查。我错过了你的类别从0开始。因此,您希望在类别长度小于或等于6时运行循环。 - Edward Romero
1
@Bolmstead 这完全取决于您想要循环何时结束。因此,如果您只想要6个项目,则需要将其设置为小于6,因为您的迭代器从0开始。否则,当前示例类别将以数组中的7个项目结束。 - Edward Romero
感谢 @EdwardRomero 的帮助。现在,一旦我运行函数,该数组就可以填充6个项目!现在是另一个问题,该数组现在可以接收重复的ID号码。我正在处理这个问题,如果我无法解决,可能会在stackoverflow上再提出另一个问题。 - personwholikestocode
1
这是因为你总是与同一个字符串进行比较,而不是随机的randomCatId。请检查带有includes的if语句所在的行。应该是categories.includes(randomCatId)。请注意我已经删除了双引号。 - Edward Romero
当然!很好的发现。一定是我从上面的console.log中复制粘贴的。再次感谢,Edward。 - personwholikestocode

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接