Javascript 给定用户字符串输入,如何检查对象是否在数组中
我正在尝试为discord构建一个参考机器人,它可以用来查找信息(Javascript 给定用户字符串输入,如何检查对象是否在数组中,javascript,Javascript,我正在尝试为discord构建一个参考机器人,它可以用来查找信息(在本例中是cars),我遇到了一个概念上的问题。用户能够运行命令查找车辆信息。用户发出的命令可能是$car1,而car1将存储在变量inputCar中。数组validCars保存所有可以查找的汽车,而car1就是其中之一car1在本例中显然不是一个字符串,而是一个具有多个字段的对象,但我需要弄清楚如何在用户输入字符串的情况下查找有关汽车的信息。我的问题有两个: 1) 我知道外部if语句不起作用,因为inputCar是用户输入的字符
在本例中是cars
),我遇到了一个概念上的问题。用户能够运行命令查找车辆信息。用户发出的命令可能是$car1
,而car1
将存储在变量
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与汽车一起存储在地图中:
const carByKey = new Map([
["car1", car1],
/*...*/
]);
然后很容易就能拿到车:
if(carByKey.has(message)){
const car = carByKey.get(message);
console.log(car.name);
//...
}
如果您确实希望获取具有相同名称且在全局范围内的javascripts变量,则可以使用window/global(取决于您的环境):
…但这是一个非常糟糕的主意。使用select而不是文本输入,这样用户只能选择有效的汽车如何?请不要在标题中添加“标签”。这就是实际标记的用途。很遗憾,我无法编辑标题,因为队列中还有其他编辑。
if(message in window){
const car = window[message];
}