使用 && 返回值

42

&& 返回值的含义是什么?

else if (document.defaultView && document.defaultView.getComputedStyle) {

    // It uses the traditional ' text-align' style of rule writing, 
    // instead of textAlign
    name = name.replace(/([A-Z]) /g, " -$1" );
    name = name.toLowerCase();
    // Get the style object and get the value of the property (if it exists)
    var s = document.defaultView.getComputedStyle(elem, " ") ;
    return s && s.getPropertyValue(name) ;

只是为了澄清:使用 && 运算符时,你不会返回一个值,而是基于其他值返回一个值。 :) - Shadow The Spring Wizard
3个回答

68

return a && b 的意思是 "如果a为假(false),返回a,否则返回b。"

它等同于下面的表达式:

if (a) return b;
else return a;

在使用返回时,使用(a) ? true : false不是更容易吗? - Alexander Kim
1
@AlexanderKim a ? true : false 就是 !!a,如 if (a) { ... }return a || b 如果 a 成立就返回 a,否则返回 b,这与此相反。 - ThaJay

16
逻辑 AND 运算符 && 的工作方式类似。如果第一个对象为假值,则返回该对象。如果它是真值,则返回第二个对象。(来源于https://www.nfriedly.com/techblog/2009/07/advanced-javascript-operators-and-truthy-falsy/
有趣的东西!
编辑: 因此,在您的情况下,如果 document.defaultView.getComputedStyle(elem, " ") 不返回有意义(“真值”)的值,则返回该值。否则,它将返回 s.getPropertyValue(name)

好的,不确定它是否尝试返回两个值。现在很清楚了。 - steve
因为你的用户名很有趣,我给你点了赞。Dinsdaaaaaaale。(实际上,你的回答也很不错) - Sean Patrick Floyd
@steve 如果要返回两个值,现在使用对象或数组很常见,因为解构已经变得如此容易。例如:function doStuff () { return [a, b] }; const [a, b] = doStuff() - ThaJay

16

AND && 运算符的作用如下:

  • 从左到右评估操作数。
  • 对于每个操作数,将其转换为布尔值。如果结果为false,则停止并返回该结果的原始值。
  • 如果已评估所有其他操作数(即所有都是truthy值),则返回最后一个操作数。

正如我所说,每个操作数都会被转换为布尔值,如果它是0,则是falsy,而其他任何不为0的值(1、56、-2等等)都是truthy。

换句话说,如果没有找到falsy值,则AND返回第一个falsy值或最后一个值。

// if the first operand is truthy,
// AND returns the second operand:
return 1 && 0 // 0
return 1 && 5 // 5

// if the first operand is falsy,
// AND returns it. The second operand is ignored
return null && 5 // null
return 0 && "no matter what"  // 0

我们还可以在一行中传递多个值。看看第一个假值是如何返回的:

return 1 && 2 && null && 3 // null
当所有值都为真值时,返回最后一个值:
return 1 && 2 && 3 // 3, the last one

您可以在此处了解有关逻辑运算符的更多信息:https://javascript.info/logical-operators


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接