我在把一个JS库加到我的工程里,今天在开发中遇到了这样的问题,请帮忙看看。
var a = new Date();
var b = a || "test";
alert(b);
问题出在b的返回值,我理解中b应该是true(我引用的库也是这个结果),可是在浏览器里执行b返回的是一个Date的Object。想问问大家,在标准中b应该是一个布尔值还是返回表达式,希望大家给出根据。谢谢!!

解决方案 »

  1.   

    在标准中b应该是一个布尔值;
    a是一个Object,"test"是一个长度4的字符串,而"||"运算符返回是一个boolean值,
    只不过,"||"运算符在运行时,如果第一个表达式值为真,那么就不会执行"||"后面的表达式了,直接返回真;
      

  2.   

    但是js不通其他语言,
    返回值: 如果第一个表达式为true,则直接返回第一个表达式的值,
           第一个false 第二个true,则返回第二个表达式的值,
           都为false的时候,返回false;
      

  3.   

    如果运算数不是boolean值,则返回的值不一定是boolean值
    如果2个运算数都是对象,则返回第一个对象
      

  4.   

    到委员会找标准了,贴出来大家看看,结贴散分!!The production LogicalORExpression : LogicalORExpression || LogicalANDExpression is evaluated as follows:
    1. Evaluate LogicalORExpression.
    2. Call GetValue(Result(1)).
    3. Call ToBoolean(Result(2)).
    4. If Result(3) is true, return Result(2).
    5. Evaluate LogicalANDExpression.
    6. Call GetValue(Result(5)).
    7. Return Result(6).
    The LogicalANDExpressionNoIn and LogicalORExpressionNoIn productions are evaluated in the same manner as the LogicalANDExpression and LogicalORExpression productions except that the contained LogicalANDExpressionNoIn, BitwiseORExpressionNoIn and LogicalORExpressionNoIn are evaluated instead of the contained LogicalANDExpression, BitwiseORExpression and LogicalORExpression, respectively.关键是下面这句!!
    NOTE
    The value produced by a && or || operator is not necessarily of type Boolean. The value produced will always be the value of one of the two operand expressions.