如何缩短我的条件语句 [英] How to shorten my conditional statements

查看:19
本文介绍了如何缩短我的条件语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很长的条件语句,如下所示:

I have a very long conditional statement like the following:

if(test.type == 'itema' || test.type == 'itemb' || test.type == 'itemc' || test.type == 'itemd'){
    // do something.
}

我想知道是否可以将此表达式/语句重构为更简洁的形式.

I was wondering if I could refactor this expression/statement into a more concise form.

知道如何实现这一目标吗?

Any idea on how to achieve this?

推荐答案

将你的值放入一个数组中,并检查你的项目是否在数组中:

Put your values into an array, and check if your item is in the array:

if ([1, 2, 3, 4].includes(test.type)) {
    // Do something
}

如果您支持的浏览器没有 Array#includes 方法,你可以使用 这个 polyfill.

If a browser you support doesn't have the Array#includes method, you can use this polyfill.

更新:既然我们现在有了 includes 方法,就没有必要再使用 ~ hack 了.只是为了有兴趣了解它是如何工作的和/或在其他人的代码中遇到它的人保留这个.

Update: Since we now have the includes method, there's no point in using the ~ hack anymore. Just keeping this here for people that are interested in knowing how it works and/or have encountered it in other's code.

除了检查 indexOf 的结果是否为 >= 0,还有一个不错的小捷径:

Instead of checking if the result of indexOf is >= 0, there is a nice little shortcut:

if ( ~[1, 2, 3, 4].indexOf(test.type) ) {
    // Do something
}

这是小提琴:http://jsfiddle.net/HYJvK/

这是如何工作的?如果在数组中找到一个项目,indexOf 返回它的索引.如果未找到该项目,它将返回 -1.在不涉及太多细节的情况下,~ 是一个 按位非运算符,它只会为 -1 返回 0.

How does this work? If an item is found in the array, indexOf returns its index. If the item was not found, it'll return -1. Without getting into too much detail, the ~ is a bitwise NOT operator, which will return 0 only for -1.

我喜欢使用 ~ 快捷方式,因为它比对返回值进行比较更简洁.我希望 JavaScript 有一个 in_array 函数,它直接返回一个布尔值(类似于 PHP),但这只是一厢情愿(更新: 现在有了.它被称为 包括.见上文).请注意,jQuery 的 inArray 在共享 PHP 的方法签名的同时,实际上模仿了原生的 indexOf 功能(这在不同情况下很有用,如果您真正想要的是索引).

I like using the ~ shortcut, since it's more succinct than doing a comparison on the return value. I wish JavaScript would have an in_array function that returns a Boolean directly (similar to PHP), but that's just wishful thinking (Update: it now does. It's called includes. See above). Note that jQuery's inArray, while sharing PHP's method signature, actually mimics the native indexOf functionality (which is useful in different cases, if the index is what you're truly after).

重要说明:使用波浪号快捷方式似乎充满争议,因为一些强烈认为代码不够清晰,应该不惜一切代价避免(请参阅对此答案的评论).如果你同意他们的观点,你应该坚持 .indexOf(...) >= 0 解决方案.

Important note: Using the tilde shortcut seems to be swathed in controversy, as some vehemently believe that the code is not clear enough and should be avoided at all costs (see the comments on this answer). If you share their sentiment, you should stick to the .indexOf(...) >= 0 solution.

JavaScript 中的整数是有符号的,这意味着最左边的位被保留为符号位;用于指示数字是正数还是负数的标志,1 为负数.

Integers in JavaScript are signed, which means that the left-most bit is reserved as the sign bit; a flag to indicate whether the number is positive or negative, with a 1 being negative.

以下是一些 32 位二进制格式的示例正数:

Here are some sample positive numbers in 32-bit binary format:

1 :    00000000000000000000000000000001
2 :    00000000000000000000000000000010
3 :    00000000000000000000000000000011
15:    00000000000000000000000000001111

现在是相同的数字,但为负数:

Now here are those same numbers, but negative:

-1 :   11111111111111111111111111111111
-2 :   11111111111111111111111111111110
-3 :   11111111111111111111111111111101
-15:   11111111111111111111111111110001

为什么负数的组合如此奇怪?简单的.负数只是正数 + 1 的倒数;将负数与正数相加应该总是产生 0.

Why such weird combinations for the negative numbers? Simple. A negative number is simply the inverse of the positive number + 1; adding the negative number to the positive number should always yield 0.

为了理解这一点,让我们做一些简单的二进制算术.

To understand this, let's do some simple binary arithmetic.

以下是我们将 -1 添加到 +1 的方法:

Here is how we would add -1 to +1:

   00000000000000000000000000000001      +1
+  11111111111111111111111111111111      -1
-------------------------------------------
=  00000000000000000000000000000000       0

这里是我们将 -15 添加到 +15 的方法:

And here is how we would add -15 to +15:

   00000000000000000000000000001111      +15
+  11111111111111111111111111110001      -15
--------------------------------------------
=  00000000000000000000000000000000        0

我们如何得到这些结果?通过定期加法,我们在学校教的方式:你从最右边的列开始,然后把所有的行加起来.如果总和大于最大的一位数(十进制为 9,但二进制为 1),我们将余数转移到下一列.

How do we get those results? By doing regular addition, the way we were taught in school: you start at the right-most column, and you add up all the rows. If the sum is greater than the greatest single-digit number (which in decimal is 9, but in binary is 1) we carry the remainder over to the next column.

现在,你会注意到,当给它的正数加上一个负数时,不全是 0 的最右边一列总是有两个 1s,当它们加在一起时会产生 2.两个的二进制表示为10,我们将1带到下一列,并在第一列放置一个0作为结果.左边的所有其他列只有一行带有 1,因此从前一列结转的 1 将再次加起来为 2, 然后会结转... 这个过程会一直重复,直到我们到达最左边的列,要结转的 1 无处可去,所以它溢出并丢失,并且我们只剩下 0 了.

Now, as you'll notice, when adding a negative number to its positive number, the right-most column that is not all 0s will always have two 1s, which when added together will result in 2. The binary representation of two being 10, we carry the 1 to the next column, and put a 0 for the result in the first column. All other columns to the left have only one row with a 1, so the 1 carried over from the previous column will again add up to 2, which will then carry over... This process repeats itself till we get to the left-most column, where the 1 to be carried over has nowhere to go, so it overflows and gets lost, and we're left with 0s all across.

这个系统叫做2's Complement.您可以在此处阅读更多相关信息:

This system is called 2's Complement. You can read more about this here:

2 的带符号整数的补码表示.

既然 2 的补码速成课程已经结束,您会注意到 -1 是唯一一个二进制表示形式为 1 的唯一数字.

Now that the crash course in 2's complement is over, you'll notice that -1 is the only number whose binary representation is 1's all across.

使用 ~ 按位非运算符,给定数字中的所有位都被反转.从反转所有位中获得 0 的唯一方法是,如果我们从 1 开始.

Using the ~ bitwise NOT operator, all the bits in a given number are inverted. The only way to get 0 back from inverting all the bits is if we started out with 1's all across.

所以,所有这些都是一种冗长的说法,如果 n-,~n 只会返回 01.

So, all this was a long-winded way of saying that ~n will only return 0 if n is -1.

这篇关于如何缩短我的条件语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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