gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:09:42 24 4
gpt4 key购买 nike

我想创建一个从 jService API 接收到的 6 个(半)随机琐事类别 ID 编号的数组。我将代码设置为迭代,将新的随机类别 ID 插入空的 categories如果尚未包含 ID,则为数组。
我已经控制台记录了变量 categories每次迭代后供引用。似乎 ID 被插入数组,但在每次迭代后被替换,留下 5 个空白数组项?相反,我尝试为 category 创建一个嵌套迭代。索引号并通过执行 category[i]=randomCatId 添加 ID ,但无法使其正常工作。推送方法不应该正常工作吗?任何有关为什么会发生这种情况的帮助将不胜感激。谢谢

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>

最佳答案

您的 for 循环没有正确检查如何结束循环,因此它将永远运行。
将您的 for 循环更改为

for (i=0;categories.length<=6;i++)

关于javascript - 为什么数组不接受推送变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63769463/

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