Javascript 如何从数组中获取元素。
几个小时前我发布了这个问题: 我还有一个问题:如何从给定索引的数组中获取特定元素?我想在不使用大型开关的情况下为每个元素编写一条自定义消息:Javascript 如何从数组中获取元素。,javascript,switch-statement,Javascript,Switch Statement,几个小时前我发布了这个问题: 我还有一个问题:如何从给定索引的数组中获取特定元素?我想在不使用大型开关的情况下为每个元素编写一条自定义消息: switch (lotUser | winnendLot) { case lotUser === winnendLot[0]: console.log("Je hebt " + naamArtikel[0] + " gewonnen"); break; case lotUser === winnendLot[
switch (lotUser | winnendLot) {
case lotUser === winnendLot[0]:
console.log("Je hebt " + naamArtikel[0] + " gewonnen");
break;
case lotUser === winnendLot[1]:
console.log("Je hebt " + naamArtikel[1] + " gewonnen");
break;
case lotUser === winnendLot[2]:
console.log("Je hebt " + naamArtikel[2] + " gewonnen");
break;
case lotUser === winnendLot[3]:
console.log("Je hebt " + naamArtikel[3] + " gewonnen");
break;
case lotUser === winnendLot[4]:
console.log("Je hebt " + naamArtikel[4] + " gewonnen");
break;
case lotUser === winnendLot[5]:
console.log("Je hebt " + naamArtikel[5] + " gewonnen");
break;
case lotUser === winnendLot[6]:
console.log("Je hebt " + naamArtikel[6] + " gewonnen");
break;
case lotUser === winnendLot[7]:
console.log("Je hebt " + naamArtikel[7] + " gewonnen");
break;
default:
console.log("You do not win!");
break;
}
是否可以在单个案例中使用lotUser
的数组索引提供不同的响应?也许我可以使用if/else。使用提供给您的,您所要做的就是引用数组中元素的索引,并使用该索引显示适当的消息:
var winnedIndex = winnedLot.indexOf(lotUser);
if (winnedIndex !== -1) {
console.log("Je hebt " + naamArtikel[winnedIndex] + " gewonnen");
}
else {
console.log("You do not win!");
}
看起来您可能对switch语句的用法有误解。我建议你在任何情况下阅读一篇文章,不管怎样,在你的情况下,开关似乎并不合适。您要做的是对数组中的每个元素执行一次检查,并打印一条带有数组值的语句,当该值为true时,它将显示该值。在这种情况下,以下是首选方法
for(var x=0; x<winnendLost.length; x++)
{
if(lotUser === winnendList[x])
console.log("Je hebt " + winnendList[x] + " gewonnen");
};
用于(var x=0;xAvoid|
除非您执行位运算,否则请使用|
。您能提供更多的代码吗?问题似乎出在其他地方。@Dude:我现在将|改为| | |,这没有什么区别。我不确定我是否能提供更多的代码,这是家庭作业,分发代码可能会让同学受益。问题是,这个switch语句显然不适用于案例,而是直接指向默认值,因此它不会将案例评估为true。我没有说|
会解决问题。我说这通常是个好主意。哦,哇,我没有想到这一点。非常感谢!你真的帮了我一大忙:)@JohannBehrens不是关于如何使用switch的问题?如果不是,那么这与为什么不同?这个问题很长,也不清楚。@Dude:我想我给这个问题起的名字不对,你是对的。区别在于在获胜的情况下,一个普通的信息,这个问题是关于一个特定的信息,根据I数组的ndex。@JohannBehrens为什么不问问数组的索引呢?