gpt4 book ai didi

javascript - 数组不同时如何更改类别?

转载 作者:行者123 更新时间:2023-11-30 08:19:01 26 4
gpt4 key购买 nike

我知道标题很奇怪,但我不知道如何用一句话表达我的问题。

所以我需要数组和一个文件。我合并了两个数组,所以我可以使用 Math.floor(Math.random() * number)

但是当我的文件的值来自第一个或第二个数组时,我想更改 category.innerHTML。

我尝试了 if 语句,但我猜我错了。


let fruit = ["apple", "mango", "watermelon", "peach", "banana"];

let vegetable = ["cucumber", "carrot", "potato", "celery", "radish"];

let categories = fruit.concat(vegetable);

let categoriesLength = categories.length;

let password = categories[Math.floor(Math.random() * categoriesLength)];

let category = document.querySelector(".category");

if (password <= categories[4]) {
category.innerHTML = "<p>category: fruit</p>";
} else if (password <= categories[9] && password >= categories[5]) {
category.innerHTML = "<p>category: vegetable</p>";
}

最佳答案

password <= categories[4]只是按字典顺序比较password使用字符串 banana .

相反,您可以使用 indexOf includes 像这样:

let fruit = ["apple", "mango", "watermelon", "peach", "banana"],
vegetable = ["cucumber", "carrot", "potato", "celery", "radish"],
categories = fruit.concat(vegetable),
categoriesLength = categories.length,
password = categories[Math.floor(Math.random() * categoriesLength)],
category = document.querySelector(".category");

if (categories.indexOf(password) <= 4)
category.innerHTML = "<p>category: fruit</p>";
else
category.innerHTML = "<p>category: vegetable</p>";

// Supported only in ES2016+
if (fruit.includes(password))
console.log("category: fruit")
else
console.log("category: vegetable")
<span class="category" />

关于javascript - 数组不同时如何更改类别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57083439/

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