这种简化JavaScript的开关 [英] Simplifying this JavaScript-switch

查看:122
本文介绍了这种简化JavaScript的开关的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想就一些建议如何瘦下来此开关:

I would like some advice on how to slim down this switch:

switch (lotUser | winningLot) {
        case lotUser === winningLot[0]:
        case lotUser === winningLot[1]:
        case lotUser === winningLot[2]:
        case lotUser === winningLot[3]:
        case lotUser === winningLot[4]:
        case lotUser === winningLot[5]:
        case lotUser === winningLot[6]:
        case lotUser === winningLot[7]:
            console.log("You win!");
            break;
        default:
            console.log("You do not win!");
            break;
    }

而不是

case lotUser === winningLot[0]:

我写的剧本是:

switch (lotUser | winnendLot) {
    case lotUser === winnendLot[0|1|2|3|4|5|6|7]:
        console.log("You win!");
        break;
    default:
        console.log("You do not win!");
        break;
}

我只是不知道,如果这个工程我想它的工作方式。它需要检查是否产生lotUser等于以阵列(winningLot)的值之一。如果lotUser等于winningLot数组中的值的一个或多个,就应该输出你赢了!。
可能有人请确认我的code确实给我说明?

I just don't know if this works the way I want it to work. It needs to check if the generated lotUser is equal to one of the values in an array (winningLot). If the lotUser equals one or more of the values in the winningLot array, it should output "You win!". Could someone please confirm that my code does the description I gave?

推荐答案

什么<一个href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf\">Array.prototype.indexOf()?

if (winnedLot.indexOf(lotUser) !== -1) {
  console.log("Won!");
}
else {
  console.log("Lost!");
}

它搜索存储在 lotUser 值的第一次出现的数组,并返回各自的指数。

It searches the array for the first occurrence of the value stored in lotUser and returns its respective index.

因为你不需要来算的发生,这应该是最好的办法。

Since you do not need to count the occurrences, this should be the best way.

如果你想算来,使用循环:

If you want to count them, use a loop:

var count = 0;

for (var i=0, len=winnedLot.length; i<len; i++) {
  if (winnedLot[i] === lotUser) {
    count++;
  }
}

这篇关于这种简化JavaScript的开关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆