在javascript中,一个空字符串总是false作为布尔值?

时间:2012-01-01 11:58:33

标签: javascript string boolean

在javascript中,

var a = '';
var b = (a) ? false : true;   // fixed!

var b将设置为false

这是一个可以依赖的定义行为吗?

5 个答案:

答案 0 :(得分:164)

是。 Javascript是ECMAScript的一种方言,ECMAScript语言规范明确定义了这种行为:

  

<强> ToBoolean

     

如果参数为空String(其长度为零),则结果为false;   否则结果是真的

引自http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf

答案 1 :(得分:51)

是。所有false0,空字符串''""NaNundefinednull始终评估为{ {1}};其他一切都是false

在您的示例中,评估后b为true。 (我想你错误地写了false

答案 2 :(得分:8)

var b将设置为false。这是因为空字符串在JavaScript中被视为'falsey'值,与其他值一样。

请查看http://www.sitepoint.com/javascript-truthy-falsy/的虚假值

答案 3 :(得分:8)

var a = '';
var b = (a) ? false : true;   // fixed!
console.log(b);               // => true

  

var b将设置为true

     

这是一个可以依赖的定义行为吗?

如上所述,,即条件(if表达式||中空字符串的已定义行为, &&? :,...)。 (必须应用内部 ToBoolean 操作的standard says。)

当使用比较时,评估会有所不同(参见Truth, Equality and JavaScript),即使结果大致相同

// conditional (note: evaluation to false prints false here!)
console.log('' ? true : false); // zero length     => false

// comparisons
console.log('' == true);        // +0 === 1        => false
console.log('' == false);       // +0 === +0       => true
console.log('' === true);       // different types => false
console.log('' === false);      // different types => false

说明:基本上,当==的操作数具有不同的类型时,JavaScript会根据,(using {{3)努力将它们转换为Numbers标准调用 ToNumber ToPrimitive ),然后在内部应用===。但是当您直接使用===时,类型不会被转换,因此将String与布尔值进行比较始终是false

粗略地说,JavaScript 条件 ToBoolean )测试定义的,非null,非零,非空,非假值< / strong>(一个空字符串是......空的,数字-0或+0是......零,NaN不是一个定义的数字,但是一个空的Object显然不是真的空),或者我喜欢思考,条件测试 a(真实),而==则比较明显,精心转换的 ToPrimitive ToNumber ),===查找完全相同

if (X) {}        // is X a (true) thing?
if (X == Y) {}   // are the values of X and Y same-ish?
if (X === Y) {}  // are X and Y exactly the same?

operations中有更多例子,这种区别非常重要,例如条件(非零长度,或它是)中的'0'truefalse比较中=='1' 为零)。再次true,在两种情况下都是console.log('' ? true : false); // zero length => false console.log('' == true); // +0 === 1 => false console.log('0' ? true : false); // non-zero length => true console.log('0' == true); // +0 === 1 => false console.log('1' ? true : false); // non-zero length => true console.log('1' == true); // 1 === 1 => true(它是一个东西,并且具有非零值)。

public class FormatErrorResponse : IHttpActionResult
{
    public HttpRequestMessage Request { get; set; }
    public Exception exception { get; set; }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        //Here, create the response you want to be returned when an exception occurs 

        //Here's my implementation of it where ErrorObj is my custom class which formats the exception the way I want
        var response = Request.CreateResponse<ErrorObj>(HttpStatusCode.InternalServerError, ErrorObj.GetError(exception));
        response.RequestMessage = Request;
        return Task.FromResult(response);   
    }
}

答案 4 :(得分:5)

  

可转换为false的表达式示例是那些   求值为null,0,空字符串(“”)或未定义。   (见MDN Reference