OR运算符在这个函数中的原因是什么?

What is the reason that the OR operator is in this function?

我看了下面的代码,但我不明白“||”是什么意思在这种情况下:

function factorial(numero) {
  numero = numero || 1
  return numero * factorial(numero - 1)
}

我理解逻辑运算符,但如果您传递任何参数,我觉得调用该函数没有意义。这就是为什么我的问题的原因。

这就像一个后备。如果 numerofalsy 值(false''undefinednullNaN0 ) 它会将值设置为 1.

正如我们在这两个测试中看到的那样,如果未传递值,它将使用 fallback 否则它将使用传递的值作为参数。

function test(value) {
  console.log(value || 'Not Set')
}

test()
test('Awesome')

还有更高级的方法,它们的工作方式不同但效果相似。在这里,我们可以通过使用 && 来做完全相反的事情,如果前一个命令是 truthy.

,则只会 运行 下一个项目

let items = []

function addItem(a) {
  let contains = items.includes(a)
  !contains && items.push(a)
}

addItem('cat')
addItem('dog')
addItem('pig')
addItem('cat')
addItem('cat')

console.log(items)

在上面我们使用 && 而不是 ||,所以如果 contains 为真,我们 运行 下一个命令,否则结束当前语句。

最后,我们可以将两者结合起来得到一个全新的结果:

let items = []

function addItem(a) {
  let contains = items.includes(a)
  !contains && a % 2 == 0 && items.push(a) || console.log('Item', a, 'is not valid')
}

addItem(1)
addItem(2)
addItem(10)
addItem(15)
addItem(10)
addItem(100)
addItem(102)
addItem(103)

console.log(items)

在这个例子中,如果项目不在数组中并且是偶数,我们只将项目插入数组。否则我们将输出该值不是有效插入,因为它已经在数组中,或者它不是事件。

这就是所谓的短路。 ||是 OR 运算符,但它的计算方式是看左侧(从不看右侧,因此 "short-circuiting"。

如果为真,它将使用该值。如果为假,它将使用右侧。此处,如果 'numero' 未定义,则为 false,因此将使用占位符默认值 1。

表示在JavaScript中总是表示。该语句的作用是将 numero 设置为 numero 的当前值(如果它是 truthy 值或 1 如果不是。

新语法,允许您这样做:

function factorial(numero = 1) {
    ....
}

给参数设置默认值哪个更方便

它只扩展第二个分支如果在你的情况下没有给出参数,如上所述它被称为短路评估。

像传递 numero 一样对待它,将其分配给变量 ELSE 将变量设置为 1

在 Javascript 以及其他语言中,运算符 || 定义为:

Logical OR (||) expr1 || expr2 Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true. (https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Operators/Logical_Operators)

该代码段是 shorthand 用于:

if (!numero)
    numero = 1;

因此,如果 numero 是 falsey 值(0、Nan、null、未定义或空字符串),它将设置为 1。