gpt4 book ai didi

javascript - 给定用户字符串输入,如何检查对象是否在数组中

转载 作者:行者123 更新时间:2023-11-30 20:48:19 25 4
gpt4 key购买 nike

我正在尝试为 discord 构建一个可用于查找信息(在本例中为汽车)的引用机器人,但我遇到了麻烦一个概念。用户能够运行命令来查找汽车信息。用户给出的命令可能是 $car1car1 将存储在 变量 inputCar 中。数组 validCars 包含所有可以查找的汽车,car1 就是其中之一。 car1 在这种情况下显然不是字符串,而是具有多个字段的对象,但我需要弄清楚如何在给定用户输入的字符串的情况下查找有关汽车的信息。我的问题是双重的:

1)我知道外面的if语句是行不通的,因为inputCar是用户输入的字符串,validCars数组中的对象是对象。如何正确检查用户输入的内容(以字符串格式)是否与其中一个对象的名称相匹配?

2) 现在假设我可以根据用户输入实际确定汽车是否存在于 validCars 中,我如何访问给定的字段 (name, model, color)用户输入以便打印它们?

这可能不是完成我正在尝试做的事情的最佳方式,因此欢迎任何建议。

var validCars = [car1, car2, car3, car4];

var car1 = {
name:"Corvette Stringray",
model:"2018",
color:"red"
};

/***
*** car2, car3, and car4 all have the same setup as car1, just different values.
***/

// Scan each message (client.on is discord.js jargon)
client.on("message", (message) => {

// Potential car name entered by user (message.content is discord.js jargon,
//it is just returning the string the user entered without the leading command prefix).
// e.g. the value in inputCar might be "car1" if the user wanted to see info on car1.
var inputCar = message.content.substr(1);

// SHOULD check if this is an actual car. This if statement won't work because inputCar is a string,
// and the values in validCars are not strings but objects.
if (validCars.includes(inputCar) == true)
{
// Condition when car1 is entered (there would be other cases for the other cars)
if (message.content == config.prefix + "car1")
{
// Print car1 info including name, model, and color
}
}
else
{
// Invalid car was entered by user.
}
});

最佳答案

您可能希望将汽车 ID 与汽车一起存储在 map 中:

 const carByKey = new Map([
["car1", car1],
/*...*/
]);

然后就很容易拿到车了:

  if(carByKey.has(message)){
const car = carByKey.get(message);
console.log(car.name);
//...
}

如果您真的想获得具有相同名称且在全局范围内的 javascripts 变量,可以使用 window/global(取决于您的环境):

 if(message in window){
const car = window[message];
}

....但这是一个非常非常糟糕的主意。

关于javascript - 给定用户字符串输入,如何检查对象是否在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48456565/

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