"!--" 在 JavaScript 中做什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34323527/
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 16:10:06  来源:igfitidea点击:

What does "!--" do in JavaScript?

javascriptdecrementprefix-operatornot-operator

提问by Kieran E

I have this piece of code (taken from this question):

我有这段代码(取自这个问题):

var walk = function(dir, done) {
    var results = [];

    fs.readdir(dir, function(err, list) {
        if (err)
            return done(err);

        var pending = list.length;

        if (!pending) 
            return done(null, results);

        list.forEach(function(file) {
            file = path.resolve(dir, file);
            fs.stat(file, function(err, stat) {
                if (stat && stat.isDirectory()) {
                    walk(file, function(err, res) {
                        results = results.concat(res);

                        if (!--pending)
                            done(null, results);
                    });
                } else {
                    results.push(file);

                    if (!--pending) 
                        done(null, results);
                }
            });
        });
    });
};

I'm trying to follow it, and I think I understand everything except for near the end where it says !--pending. In this context, what does that command do?

我正在努力遵循它,我想我理解一切,除了接近尾声的地方!--pending。在这种情况下,该命令有什么作用?

Edit: I appreciate all the further comments, but the question has been answered many times. Thanks anyway!

编辑:我感谢所有进一步的评论,但这个问题已被多次回答。不管怎么说,还是要谢谢你!

回答by TbWill4321

!inverts a value, and gives you the opposite boolean:

!反转一个值,并为您提供相反的布尔值:

!true == false
!false == true
!1 == false
!0 == true

--[value]subtracts one (1) from a number, and then returns that number to be worked with:

--[value]从数字中减去一 (1),然后返回要使用的数字:

var a = 1, b = 2;
--a == 0
--b == 1

So, !--pendingsubtracts one from pending, and then returns the opposite of its truthy/falsy value (whether or not it's 0).

因此,!--pending从待定值中减去 1,然后返回其真/假值的相反值(无论是否为0)。

pending = 2; !--pending == false 
pending = 1; !--pending == true
pending = 0; !--pending == false

And yes, follow the ProTip. This may be a common idiom in other programming languages, but for most declarative JavaScript programming this looks quite alien.

是的,请遵循 ProTip。这在其他编程语言中可能是一个常见的习惯用法,但对于大多数声明式 JavaScript 编程来说,这看起来很陌生。

回答by Amit

That's not a special operator, it's 2 standard operators one after the other:

这不是一个特殊的运算符,它是一个接一个的 2 个标准运算符:

  1. A prefix decrement (--)
  2. A logical not (!)
  1. 前缀递减 ( --)
  2. 逻辑非 ( !)

This causes pendingto be decremented and then tested to see if it's zero.

这会导致pending递减,然后测试它是否为零。

回答by Stig Hemmer

A number of answers describes whatthis command does, but not whyit is done that way here.

许多答案描述这个命令的作用,但没有描述为什么在这里这样做。

I come from the C world, and I read !--pendingas "count down pendingand check if it is zero" without really thinking about it. It is an idiom that I think programmers in similar languages should know.

我来自 C 世界,我读到!--pending“倒计时pending并检查它是否为零”而没有真正考虑它。这是我认为使用类似语言的程序员应该知道的习语。

The function uses readdirto get a list of files and subdirectories, which I will collectively call "entries".

该函数用于readdir获取文件和子目录的列表,我将它们统称为“条目”。

The variable pendingkeeps track of how many of these remains to be processed. It starts out as the length of the list, and counts downward towards zero as each entry is processed.

该变量pending会跟踪其中有多少需要处理。它从列表的长度开始,并在处理每个条目时向下计数到零。

These entries may be processed out of order, which is why it is necessary to count down rather than just using a simple loop. When allthe entries have been processed the callback doneis called to notify the original caller of this fact.

这些条目可能会被乱序处理,这就是为什么有必要倒计时而不是仅仅使用简单的循环。当所有的项目都已经被处理的回调done被调用,通知这个事实原始调用者。

In the first call to doneis prepended with return, not because we want to return a value, but simply to make the function stop executing at that point. It would have been cleaner code to drop the returnand put the alternative in an else.

在第一次调用中,done前面加上了return,不是因为我们想要返回一个值,而只是为了让函数在那个时候停止执行。删除return并将替代项放在else.

回答by Lucas

It's a shorthand.

这是一个简写。

!is "not".

!不是”。

--decrements a value.

--减少一个值。

So !--checks if the value obtained from negating the result of decrementing a value is false.

因此,!--检查从对值递减的结果取反得到的值是否为假。

Try this:

尝试这个:

var x = 2;
console.log(!--x);
console.log(!--x);

The first is false, since the value of x is 1, the second is true, since the value of x is 0.

第一个为假,因为 x 的值为 1,第二个为真,因为 x 的值为 0。

Side note: !x--would check if x is false first, and then decrement it.

旁注: !x--将首先检查 x 是否为假,然后将其递减。

回答by Sterling Archer

!is the JavaScript NOToperator

!是 JavaScript NOT运算符

--is a pre-decrement operator. So,

--是预减运算符。所以,

x = 1;
if (!x) // false
if (!--x) // becomes 0 and then uses the NOT operator,
          // which makes the condition to be true

回答by james turner

if(!--pending)

means

方法

if(0 == --pending)

means

方法

pending = pending - 1;
if(0 == pending)

回答by Brendan Abel

It's the not operator followed by the in-place pre-decrementer.

它是 not 运算符,后跟就地预减量器。

So if pendingwas an integer with a value of 1:

所以如果pending是一个值为 1 的整数:

val = 1;
--val; // val is 0 here
!val // evaluates to true

回答by MinusFour

It merely decreases pendingby one and obtains its logical complement (negation). The logical complement of any number different than 0 is false, for 0 it is true.

它只是减pending一并获得其逻辑补码(否定)。任何不同于 0 的数的逻辑补码是false,对于 0 是true

回答by Ben Aubin

Explanation

解释

This is 2 operators, a !and a --

这是 2 个运算符,a!和 a--

!--x 

So, the --decrements x by 1, then the !returns true if x is now 0 (or NaN...), false if it isn't. You might read this idiom something like "we decrement x and if that makes it zero..."

因此,将--x 减 1,!如果 x 现在为 0(或 NaN...),则返回 true,否则返回 false。你可能会读这个习语,比如“我们递减 x,如果这使它为零......”

If you wanted to make it more readable, you can:

如果你想让它更具可读性,你可以:

var x = 1
x = x - 1   
if(!x){ //=> true
    console.log("I understand `!--` now!") 
}
x //=> 0

Try it out:

试试看:

/* This is an example of the above, you can read this, but it is not needed for !-- */function interactive(a){$("span.code").keydown(function(e){if(13==(e.keyCode||e.which)){var t=$(this);t.clone().html("code").insertAfter(t.next().next()).show().focus().after(template.clone().removeClass("result-template").show()).next().after("<br>"),interactive(),e.preventDefault()}}).keyup(function(e){13!=(e.keyCode||e.which)&&run()})}var template=$(".result-template").hide(),code=$("span.code");code.attr("contenteditable","true").each(function(e,t){template.clone().removeClass("result-template").insertAfter(t)}),interactive(),$.fn.reduce=[].reduce;function run(){var b=!1,context={};$("span.code").each(function(){var a=$(this),res=a.next().show().removeClass("error");try{with(context)res.html(b?"":"  //=> "+eval(a.text()))}catch(e){b=e,res.html("  Error: "+b.message).addClass("error")}})};run();
/* This is an example of the above, you can read this, but it is not needed for !-- */span.result.error{display:block;color:red}.code{min-width:10px}body{font-family:Helvetica,sans-serif}
<!-- This is an example of the above, you can read this, but it is not needed for `!--` --><span class="result result-template"> //=> unknown </span> <h2>Edit This Code:</h2><code><span class="code">x = 1</span><br><span class="code">!--x</span><br><span class="code"> x </span><br></code> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Fiddle (Try Out Code)

小提琴(试用代码)

回答by Michael Geary

The real problem here is the lack of a space between the two operators !and --.

这里真正的问题是两个运算符!和之间缺少空格--

I don't know why people get it in their heads that you can't ever use a space after the !operator. I think it comes from rigid application of mechanical whitespace rules instead of common sense. Just about every coding standard I've seen prohibits spaces after all unary operators, but why?

我不知道为什么人们会认为你不能在!操作符后面使用空格。我认为它来自机械空白规则的严格应用,而不是常识。几乎我见过的所有编码标准都禁止在一元运算符之后使用空格,但为什么呢?

If there were ever a case where you clearly needthat space, this is one.

如果在某个情况下您显然需要该空间,那么这就是其中之一。

Consider this bit of code:

考虑这段代码:

if (!--pending)
    done(null, results);

Not only are !and --mashed together, you've got that (slammed against them too. No wonder it's hard to tell what is connected to what.

不仅是!--捣碎在一起,你也已经(对他们进行了猛烈抨击。难怪很难说出什么与什么有关。

A bit more whitespace makes the code much more clear:

多一点空白使代码更清晰:

if( ! --pending )
    done( null, results );

Sure, if you're used to mechanical rules like "no space inside parens" and "no space after a unary operator", this may seem a bit foreign.

当然,如果您习惯了诸如“括号内没有空格”和“一元运算符后没有空格”之类的机械规则,这可能看起来有点陌生。

But look at how the extra whitespace groups and separates the various parts of the ifstatement and expression: You've got --pending, so the --is clearly its own operator and is tied closely to pending. (It decrements pendingand returns the decremented result.) Then you've got the !separated from that so it's obviously a distinct operator, negating the result. Finally, you've got if(and )surrounding the whole expression to make it an ifstatement.

但是看看额外的空格如何分组和分隔if语句和表达式的各个部分:你有--pending, 所以 the--显然是它自己的运算符并且与pending. (它递减pending并返回递减后的结果。)然后你已经从中!分离出来,所以它显然是一个不同的运算符,否定结果。最后,您已经获得if()包围了整个表达式以使其成为一个if声明。

And yes, I removed the space between ifand (, because the (belongsto the if. This (isn't part of some kind of (!--syntax as it appears to be in the original, the (if part of the syntax of the ifstatement itself.

是的,我删除之间的空间if(,因为(所属if。这(不是某种(!--语法的一部分,因为它似乎是原始的,(if语句本身语法的if 部分。

The whitespace here serves to communicate the meaning, instead of following some mechanical coding standard.

这里的空格用于传达含义,而不是遵循一些机械编码标准。