! JavaScript中的运算符 [英] ! operator in JavaScript

查看:87
本文介绍了! JavaScript中的运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在感到困惑! JavaScript中的运算符。我的理解是!运算符仅对布尔运算。但是对我的一个答案的评论说它可以对任何东西进行操作并返回一个布尔值,这在我之后恰好是真的做了一些测试。

I am now confused about ! operator in JavaScript. My understanding was ! operator operates only on boolean. But a comment to one of my answers says it can operate on anything and returns a boolean, which happened to be true after I did some tests.

alert(!undefined); //true
alert(!function(){}); //false
alert(!{}); //false
alert(!null); //true
alert(!()); //crash
alert(!"false"); //false
alert(!false)​;​​​​​​​​​​​​ //true​​​​​​​​​​​​​​​​​​

有人可以帮我概括行为!运营商。

Can somebody help me generalize the behavior of ! operator.

编辑

更令人困惑的事情:

​alert( new String() == ""); //true
alert(!""); //true
alert(! new String()); //false

如何?

推荐答案

做你的想法:转是真是假,反之亦然。奇怪的行为与Javascript如何将字面上的任何内容转换为 true false

! does what you think: turns true to false and vice-versa. The weird behavior has to do with how Javascript can convert literally anything to true or false.

http://11heavens.com/falsy-and -truthy-in-javascript

与C类似(只有更糟),所有值都可以提升为true或false。你想要的可耻术语是真实的和虚假的,或真实性和虚假性。 Truthy意味着某些东西转化为真实,虚假意味着某些东西转化为虚假。所有值都是真实的,除了 null undefined 0 NaN ,以及... false

Like in C (only worse) all values can be promoted to true or false. The googlable terms you want are "truthy" and "falsy," or "truthiness" and "falsiness." Truthy means something converts to true, falsy means something converts to false. All values are truthy except null, undefined, 0, "", NaN, and... false

这个链接有更多有趣的例子:

This link has more fun examples:

http://www.sitepoint.com/javascript-truthy-falsy/

这个网站非常喜欢用这里有趣的行为来做病态的事情:

And this site really likes doing pathological things with the funny behavior here:

http ://wtfjs.com

另请注意 == 确实努力使事物具有可比性而 === 只返回 false 如果事情不具有可比性。 Crockford在 Javascript:好的部分建议不要完全使用 ==

Also note that == really tries hard to make things comparable whereas === just returns false if the things aren't comparable. Crockford in Javascript: The Good Parts recommends not using == entirely.

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

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