javascript 使用&&返回值

ndh0cuux  于 2023-05-12  发布在  Java
关注(0)|答案(3)|浏览(125)

返回一个带有&&的值是什么意思?

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) ;
u0sqgete

u0sqgete1#

return a && b的意思是“如果a是假的,返回a;如果a是真的,返回b”。
它相当于

if (a) return b;
else return a;
lawou6xi

lawou6xi2#

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

6yt4nkrj

6yt4nkrj3#

AND &&运算符执行以下操作:

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

正如我所说的,每个操作数都被转换为布尔值,如果它是0,它是falsy,而所有其他不同于0的值(1,56,-2等)都是truthy
换句话说,AND返回第一个false值,如果没有找到,则返回最后一个值。

// 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

当所有值都为truthy时,返回最后一个值:

return 1 && 2 && 3 // 3, the last one

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

相关问题