&& 是一个logical operator。这将测试一个值是否为truthy or falsy。这篇链接文章解释了虚假值等于undefined、null、NaN、0、"" 和 false。
从左到右检查逻辑表达式。如果表达式的任何部分被评估为 falsy,则表达式的其余部分将不被评估。在您的示例中,该值始终是真实的。在这里,我们可以分解您的第一个表达式:
f = 1 && 2 && 3;
f = 1 /* Okay, 1 is a truthy value, lets continue... */
f = 2 /* Still truthy, let's continue... */
f = 3 /* Still truthy, we've reached the end of the expression, f = 3. */
如果 3 之前的任何值是虚假的,则表达式将结束。要实际展示这一点,只需将您的变量重新声明为:
f = 1 && 2 && 0 && 3;
这里的 0 是一个假值(如上所述)。此处表达式的执行将在 0 处结束:
f = 1 /* Okay, 1 is a truthy value, lets continue... */
f = 2 /* Still truthy, let's continue... */
f = 0 /* Hey, this is falsy, lets stop here, f = 0. */
f = 3 /* We never get here as the expression has ended */
这里 f 最终为 0。
在您的jQuery.Topic() 示例中,&& 用于确保id 实际存在:
topic = id && topics[id]
我们可以用同样的方式分解:
/* Assume this is your topics array: */
topics = ["", "My First Topic", "My Second Topic"];
/* If we pass in the value 1 as "jQuery.Topic(1)": */
topic = id && topics[id]
topic = 1 /* This is truthy, let's continue... */
topic = topics[1] /* topics[1] === "My First Topic" */
/* Now lets assume we pass in nothing as "jQuery.Topic()": */
topic = id && topics[id]
topic = null /* This is falsy, let's stop here, topic = null. */
以下if 语句仅在topic 为真时才有效。在第一个示例中,topic 的值设置为非空字符串。在第二个示例中,topic 为 null,这是假的。