Javascript 有没有更好的写法 v = (v == 0 ? 1 : 0);

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6911235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:43:54  来源:igfitidea点击:

Is there a better way of writing v = (v == 0 ? 1 : 0);

javascriptvariablescoding-styletoggle

提问by Ollie Glass

I want to toggle a variable between 0 and 1. If it's 0 I want to set it to 1, else if it's 1 I want to set it to 0.

我想在 0 和 1 之间切换一个变量。如果它是 0,我想把它设置为 1,否则如果它是 1,我想把它设置为 0。

This is such a fundamental operation that I write so often I'd like to investigate the shortest, clearest possible way of doing it. Here's my best so far:

这是一个如此基本的操作,我经常写,我想研究一下最短、最清晰的方法。到目前为止,这是我最好的:

v = (v == 0 ? 1 : 0);

Can you improve on this?

你能改进吗?

Edit: the question is asking how to write the above statement in the fewest characters while retaining clarity - how is this 'not a real question'? This wasn't intended to be a code-golf exercise, though some interesting answers have come out of people approaching it as golf - it's nice to see golf being used in a constructive and thought-provoking manner.

编辑:问题是问如何在保持清晰度的同时用最少的字符写出上述语句 - 这怎么可能“不是一个真正的问题”?这并不打算成为一个代码高尔夫练习,尽管一些有趣的答案来自将它视为高尔夫的人 - 很高兴看到以建设性和发人深省的方式使用高尔夫。

回答by Guffa

You can simply use:

您可以简单地使用:

v = 1 - v;

This of course assumes that the variable is initialised properly, i.e. that it only has the value 0 or 1.

这当然假设变量已正确初始化,即它只有值 0 或 1。

Another method that is shorter but uses a less common operator:

另一种较短但使用不太常见的运算符的方法:

v ^= 1;

Edit:

编辑:

To be clear; I never approached this question as code golf, just to find a short way of doing the task without using any obscuring tricks like side effects of operators.

要清楚;我从来没有像代码高尔夫一样处理这个问题,只是为了找到一种简单的方法来完成任务,而不使用任何像操作符的副作用这样的模糊技巧。

回答by Quentin

Since 0is a falsevalue and 1is a truevalue.

因为0是一个false值并且1是一个true值。

v = (v ? 0 : 1);

If you are happy to use trueand falseinstead of numbers

如果您乐于使用truefalse而不是数字

v = !v;

or if they must be numbers:

或者如果它们必须是数字:

v = +!v; /* Boolean invert v then cast back to a Number */

回答by Prusse

v = (v + 1) % 2and if you need to cycle through more values just change 2for (n + 1). Say you need to cycle 0,1,2 just do v = (v + 1) % 3.

v = (v + 1) % 2如果你通过更多的值需要周期只是改变2(n + 1)。假设您需要循环 0,1,2 就可以了v = (v + 1) % 3

回答by Daniel

You could write a function for it and use it like:

您可以为它编写一个函数并使用它:

v = inv(v)

v = inv(v)

回答by Brian

If you don't care about any possibility other than 1:

如果您不关心除 1 以外的任何可能性:

v = v ? 0 : 1;

In the above case, v will end up being 1 if v is 0, false, undefined or null. Take care using this kind of approach - v will be 0 even if v is "hello world".

在上述情况下,如果 v 为 0、false、undefined 或 null,则 v 最终为 1。小心使用这种方法 - 即使 v 是“hello world”,v 也会是 0。

回答by Ray

Lines like v = 1 - v, or v ^= 1or v= +!vwill all get the job done, but they constitute what I would refer to as hacks. These are not beautiful lines of code, but cheap tricks to have the intended effect. 1 - vdoes not communicate "toggle the value between 0 and 1". This makes your code less expressive and introduces a place (albeit a small one) where another developer will have to parse your code.

诸如v = 1 - v, or v ^= 1orv= +!v之类的行都可以完成工作,但它们构成了我所说的 hacks。这些不是漂亮的代码行,而是达到预期效果的廉价技巧。1 - v不传达“在 0 和 1 之间切换值”。这会降低您的代码的表现力,并引入一个地方(尽管很小),其他开发人员必须在其中解析您的代码。

Having instead a function like v = toggle(v)communicates the intent at the quickest glance.

相反,拥有类似的功能可以v = toggle(v)最快地一目了然地传达意图。

回答by Andrew Stacey

(Honesty and mathematical integrity - given the number of votes on this "answer" - have led me to edit this answer. I held off as long as possible because it was intended as a short quip and not as anything "deep" so putting in any explanation seemed counter to the purpose. However, the comments are making it clear that I should be clear to avoid misunderstanding.)

诚实和数学完整性 - 鉴于对这个“答案”的投票数量 - 使我编辑了这个答案。我尽可能地推迟,因为它是一个简短的讽刺而不是任何“深刻”的东西,所以投入任何解释似乎都与目的背道而驰。但是,评论清楚地表明我应该清楚以避免误解。

My original answer:

我的原答案:

The wording of this part of the specification:

本部分规范的措辞:

If it's 0, I want to set it to 1, else set it to 0.

如果是0,我想把它设置为1,否则设置为0。

implies that the most accurate solution is:

意味着最准确的解决方案是:

v = dirac_delta(0,v)


First, the confession: I didget my delta functions confused. The Kronecker delta would have been slightly more appropriate, but not by much as I wanted something that was domain-independent (the Kronecker delta is mainly used just for integers). But I really shouldn't have used delta functions at all, I should have said:

首先,坦白:我确实混淆了我的 delta 函数。Kronecker delta 会稍微合适一些,但不是我想要的与域无关的东西(Kronecker delta 主要仅用于整数)。但我真的不应该使用 delta 函数,我应该说:

v = characteristic_function({0},v)

Let me clarify. Recall that a functionis a triple, (X,Y,f), where Xand Yare sets (called the domainand codomainrespectively) and fis a rule that assigns an element of Yto each element of X. We often write the triple (X,Y,f)as f: X → Y. Given a subset of X, say A, there is a characteristic functionwhich is a function χA: X → {0,1}(it can also be thought of as a function to a larger codomain such as ℕ or ℝ). This function is defined by the rule:

让我澄清一下。回想一下,函数是一个三元组,(X,Y,f),其中XY是集合(分别称为和余),f是将Y的元素分配给X 的每个元素的规则。我们经常将三元组(X,Y,f) 写f: X → Y。给定X 的一个子集,比如说A,有一个特征函数,它是一个函数χ A: X → {0,1}(它也可以被认为是一个更大的 codomain,如 ℕ 或 ℝ 的函数)。该函数由规则定义:

χA(x) = 1if x ∈ Aand χA(x) = 0if x ∉ A.

χ A(x) = 1如果x ∈ A并且χ A(x) = 0如果x ∉ A

If you like truth tables, it's the truth table for the question "Is the element xof Xan element of the subset A?".

如果你喜欢真值表,它是问题“ X的元素x是子集A的元素吗?”的真值表。

So from this definition, it's clear that the characteristic function is what is needed here, with Xsome big set containing 0 and A = {0}. That's what I shouldhave written.

所以根据这个定义,很明显特征函数是这里需要的,X 是一些包含 0 和A = {0} 的大集合。那是我应该写的。

And so to delta functions. For this, we need to know about integration. Either you already know it, or you don't. If you don't, nothing I can say here will tell you about the intricacies of the theory, but I can give a one sentence summary. A measureon a set Xis in essence "that which is needed to make averages work". That is to say that if we have a set Xand a measure μon that set then there is a class of functions X → ℝ, called measurable functionsfor which the expression Xf dμmakes sense and is, in some vague sense, the "average" of fover X.

delta 函数也是如此。为此,我们需要了解集成。要么你已经知道,要么你不知道。如果你不知道,我在这里说什么都不会告诉你理论的复杂性,但我可以给你一句话总结。对集合X 的度量本质上是“使平均值起作用所需的度量”。也就是说,如果我们有一个集合X和该集合上的一个测度μ,那么就有一类函数X → ℝ,称为可测函数,对于其表达式Xf dμ有意义,并且在某种模糊的意义上是,fX 上的“平均值” 。

Given a measure on a set, one can define a "measure" for subsets of that set. This is done by assigning to a subset the integral of its characteristic function (assuming that this is a measurable function). This canbe infinite, or undefined (the two are subtly different).

给定一个集合上的度量,可以为该集合的子集定义一个“度量”。这是通过将其特征函数的积分分配给子集来完成的(假设这是一个可测量的函数)。这可以是无限的,也可以是未定义的(两者略有不同)。

There are lots of measures around, but there are two that are important here. One is the standard measureon the real line, ℝ. For this measure, then f dμis pretty much what you get taught in school (is calculus still taught in schools?): sum up little rectangles and take smaller and smaller widths. In this measure, the measure of an interval is its width. The measure of a point is 0.

周围有很多措施,但这里有两个很重要。一个是实线上的标准度量,ℝ。对于这个度量,那么f dμ几乎就是你在学校里学到的东西(微积分还在学校里教吗?):总结小矩形并取越来越小的宽度。在这个度量中,间隔的度量是它的宽度。点的度量为 0。

Another important measure, which works on anyset, is called the point measure. It is defined so that the integral of a function is the sumof its values:

另一个适用于任何集合的重要度量称为点度量。它被定义为函数的积分是其值的总和

Xf dμ = ∑x ∈Xf(x)

Xf dμ = ∑ x ∈Xf(x)

This measure assigns to each singleton set the measure 1. This means that a subset has finitemeasure if and only if it is itself finite. And very few functions have finite integral. If a function has a finite integral, it must be non-zero only on a countablenumber of points. So the vast majority of functions that you probably know do not have finite integral under this measure.

该度量为每个单例集分配度量 1。这意味着子集具有有限度量当且仅当它本身是有限的。并且很少有函数具有有限积分。如果函数具有有限积分,则它必须仅在数点上非零。因此,您可能知道的绝大多数函数在此度量下都没有有限积分。

And now to delta functions. Let's take a very broad definition. We have a measurable space (X,μ)(so that's a set with a measure on it) and an element a ∈ X. We "define" the delta function(depending on a) to be the "function" δa: X → ℝwith the property that δa(x) = 0if x ≠ aand Xδadμ = 1.

现在是 delta 函数。让我们做一个非常宽泛的定义。我们有一个可测空间(X,μ)(所以这是一个带有测度的集合)和一个元素a ∈ X。我们将delta 函数(取决于a)“定义”为“函数” δ a: X → ℝ具有δ a(x) = 0如果x ≠ aXδ adμ = 1 的特性

The most important fact about this to get a-hold of is this: The delta function need not be a function. It is notproperly defined: I have not said what δa(a)is.

要掌握的最重要的事实是: delta 函数不必是 function。它没有正确定义:我没有说δ a(a)是什么。

What you do at this point depends on who you are. The world here divides in to two categories. If you are a mathematician, you say the following:

你在这一点上做什么取决于你是谁。这里的世界分为两类。如果您是数学家,请说以下内容:

Okay, so the delta function might not be defined. Let's look at its hypothetical properties and see if we can find a proper home for it where it isdefined. We can do that, and we end up with distributions. These are not(necessarily) functions, but are things that behave a little like functions, and often we can work with them as if they were functions; but there are certain things that they don't have (such as "values") so we need to be careful.

好的,所以可能没有定义 delta 函数。让我们来看看它的假设性,看看我们是否能够找到合适的住所为它在那里它定义。我们可以做到这一点,我们最终得到了分布。这些不是(必然)函数,而是行为有点像函数的东西,而且我们经常可以将它们当作函数来使用;但是有些东西他们没有(例如“价值观”),所以我们需要小心。

If you are not a mathematician, you say the following:

如果您不是数学家,请说以下内容:

Okay, so the delta function might not be properly defined. Who says so? A bunch of mathematicians? Ignore them! What do they know?

好的,所以可能没有正确定义 delta 函数。谁这么说的?一群数学家?别理他们!他们知道什么?

Having now offended my audience, I shall continue.

现在冒犯了我的听众,我将继续。

The dirac deltais usually taken to be the delta function of a point (often 0) in the real line with its standard measure. So those who are complaining in the comments about me not knowing my deltas are doing so because they are using this definition. To them, I apologise: although I can wriggle out of that by using the Mathematician's defence(as popularised by Humpty Dumpty: simply redefine everything so that it is correct), it is bad form to use a standard term to mean something different.

狄拉克δ通常取为与它的标准度量实线上的点(通常0)的δ函数。所以那些在评论中抱怨我不知道我的增量的人这样做是因为他们使用了这个定义。我向他们道歉:虽然我可以通过使用数学家的辩护来摆脱这一点(正如Humpty Dumpty所流行的那样:简单地重新定义一切以使其正确),但使用标准术语来表示不同的意思是不好的形式。

But there isa delta function which does do what I want it to do and it is that which I need here. If I take a point measureon a set Xthen there isa genuine function δa: X → ℝwhich satisfies the criteria for a delta function. This is because we are looking for a function X → ℝwhich is zero except at aand such that the sum of all of its values is 1. Such a function is simple: the only missing piece of information is its value at a, and to get the sum to be 1 we just assign it the value 1. This is none other than the characteristic function on {a}. Then:

但是,它确实做我想做的事情,它是我在这里需要一个δ函数。如果我采取点措施上的一组X一个真正的函数δ一个:X→ℝ其满足用于delta函数的标准。这是因为我们正在寻找一个函数X → ℝ,除了在a处为零,并且它的所有值的总和为 1。这样的函数很简单:唯一缺少的信息是它在a值,并且为了使总和为 1,我们只需将值 1 赋值给它。这正是{a}上的特征函数。然后:

Xδadμ = ∑x ∈ Xδa(x) = δa(a) = 1.

Xδ adμ = ∑ x ∈ Xδ a(x) = δ a(a) = 1。

So in this case, for a singleton set, the characteristic function and the delta function agree.

所以在这种情况下,对于单例集,特征函数和 delta 函数是一致的。

In conclusion, there are three families of "functions" here:

总之,这里有三个“函数”家族:

  1. The characteristic functions of singleton sets,
  2. The delta functions,
  3. The Kronecker delta functions.
  1. 单例集的特征函数,
  2. delta 函数,
  3. Kronecker delta 函数。

The secondof these is the most general as any of the others is an example of it when using the point measure. But the first and third have the advantage that they are always genuine functions. The third is actually a special case of the first, for a particular family of domains (integers, or some subset thereof).

其中的第二个是最通用的,因为在使用点度量时,其他任何一个都是它的一个例子。但是第一个和第三个的优点是它们总是真正的函数。第三个实际上是第一个的特例,用于特定的域家族(整数或其某个子集)。

So, finally, when I originally wrote the answer I wasn'tthinking properly (I wouldn't go so far as to say that I was confused, as I hope I've just demonstrated I doknow what I'm talking about when I actually think first, I just didn't think very much). The usual meaning of the dirac delta is not what is wanted here, but one of the points of my answer was that the input domain was notdefined so the Kronecker delta would also not have been right. Thus the best mathematicalanswer (which I was aiming for) would have been the characteristicfunction.

所以,最后,当我最初写我的回答并没有想正常(我不会走那么远,说我糊涂,我希望我刚刚证明我知道我在说什么时候我其实是先想的,我只是没有想太多)。狄拉克三角洲的通常含义是不是在这里想要的,但我的答案的要点之一是,输入域是没有定义,因此Kronecker符号也将不会是正确的。因此,最好的数学答案(我的目标)就是特征函数。

I hope that that is all clear; and I also hope that I never have to write a mathematical piece again using HTML entities instead of TeX macros!

我希望这一切都清楚了;我也希望我再也不用用 HTML 实体而不是 TeX 宏来写数学了!

回答by Paul

You could do

你可以做

v = Math.abs(--v);

The decrement sets the value to 0 or -1, and then the Math.absconverts -1 to +1.

递减将值设置为 0 或 -1,然后Math.abs将 -1 转换为 +1。

回答by Mouna Cheikhna

in general whenever you need to toggle between two values , you can just subtract the current value from the sum of the two toggle values :

一般来说,每当您需要在两个值之间切换时,您只需从两个切换值的总和中减去当前值即可:

    0,1 -> v = 1 - v
    1,2 -> v = 3 - v
    4,5 -> v = 9 - v 
    0,1 -> v = 1 - v
    1,2 -> v = 3 - v
    4,5 -> v = 9 - v 

回答by Michael Berkowski

If it must be the integer 1 or 0, then the way you're doing it is fine, though parentheses aren't needed. If these a are to be used as booleans, then you can just do:

如果它必须是整数 1 或 0,那么您这样做的方式就可以了,尽管不需要括号。如果这些 a 被用作布尔值,那么你可以这样做:

v = !v;