什么是“!”运算符在javascript中与非布尔变量一起使用时的意思? [英] What does "!" operator mean in javascript when it is used with a non-boolean variable?

查看:162
本文介绍了什么是“!”运算符在javascript中与非布尔变量一起使用时的意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读javascript代码时,我一直看到用于非布尔变量的运算符。以下是未使用的代码示例。

While reading through javascript codes I've been seeing the ! operator used for non boolean variables. Here is an example of code not used in.

/**
 * loads a resource from a url
 * @param {string} url the url of the resource to load
 * @param {string} relativeTo the url to load relative to
 * @param {function} callback thefunction to call once the file is loaded
 * @private
 */
 GLGE.Wavefront.prototype.loadFile=function(url,relativeTo,callback){
    if(this.relativeTo && !relativeTo) relativeTo=this.relativeTo; //<-- used on a string?
    else this.relativeTo=url;
    if(!callback) callback=this.loaded;    //<-- used on a function?
    var req = new XMLHttpRequest();
    if(req) {
               // request handling code                
            }
        };
        req.open("GET", url, true);
        req.send("");
    }   
}

在这个库里我见过很多用途以这种方式操作。

In this library I've seen many uses of this operator in this manner.

有人可以解释当字符串,对象或函数的'not'函数不是像集合一样的布尔集的一半时,是否可以确定; true false

Can someone explain how/if the 'not' function of a string, object or function can be determined when it isn't one half of a Boolean set like the set; true and false?

推荐答案

在JavaScript中,一元否定运算符()将转换它的操作数基于该语言的(有点令人困惑的)规则(例如,ECMA-262第5版)的布尔值。 这篇关于JavaScript语法的文章显示了类型转换如何发生的一些示例。

In JavaScript, the unary negation operator (!) will convert its operand into a boolean based on the (somewhat confusing) rules of the language (e.g., ECMA-262 5th Edition). This article on JavaScript syntax shows some examples of how the type conversion happens.

基本上,这是测试非真实性的简单方法;看似虚假的值(例如 false null 0 NaN ,空字符串等)在被逻辑否定之前将被转换为 false ,反之亦然。您可以使用布尔构造函数显式测试真实性:

Basically, it's an easy way to test for non-"truthiness"; seemingly false values (e.g. false, null, 0, NaN, the empty string, etc.) will be converted to false before being logically negated, and vice versa. You can test for "truthiness" explicitly by using the Boolean constructor:

Boolean(null); // => false
Boolean(NaN); // => false
Boolean(""); // => false
Boolean(0); // => false
Boolean(1); // = >true
Boolean("123"); // => true
Boolean(new Object()); // => true
Boolean(function(){}); // => true

这篇关于什么是“!”运算符在javascript中与非布尔变量一起使用时的意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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