我想创建一个包含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>
for (i=0;categories.length=6;i++)
- 中间子句应该是categories.length < 6
,不是吗?实际上,我认为这应该是一个while
循环:while(categories.length < 6)
。 - Robin Zigmond