不理解特定情况下的逻辑运算符

Not understanding logical operators in a specific situation

我正在查看另一个人的代码,发现这个特定部分我不明白逻辑运算符的用途。 (请注意,我仍然从 JavaScript 开始,但在寻求您的帮助之前也做了尽可能多的研究。)

const createStream = (options) => {
  const stream = new PassThrough({
    highWaterMark: options && options.highWaterMark || null,
  });
  stream.destroy = () => { stream._isDestroyed = true; };
  return stream;
}; 

因此,据我了解,这基本上是一个函数 createStream(options),它创建了一个名为 stream 的变量,它是一个 stream.PassThrough 对象。

现在,让我有点烦恼的部分是 highWaterMark: options && options.highWaterMark || null, 部分。 我根本不明白这些。例如,我知道如何在 if() 语句中使用逻辑运算符,但这对我来说没有意义,而且我在网上找不到很多东西来解释这一点。

感谢我能得到的任何帮助。

&&|| 都有 same operator precedence 并且从左到右操作。所以

highWaterMark: options && options.highWaterMark || null,

等同于

highWaterMark: (options && options.highWaterMark) || null,

此外,请记住,如果左侧为假,&& 将解析为左侧,否则解析为右侧。所以如果 optionsundefined(options && options.highWaterMark) 解析为 undefined

那里需要 &&,因为如果 options 参数不存在(例如 undefinednull),只需执行

highWaterMark: options.highWaterMark || null,

会抛出错误,因为您无法访问 undefinednull.

的属性

然后,对于||部分:如果左侧为真,则解析到左侧,否则解析到右侧。所以有两条可能的路径:

// options starts out undefined
  highWaterMark: options && options.highWaterMark || null,
// equivalent to
  highWaterMark: (options && options.highWaterMark) || null,
  highWaterMark: (undefined && options.highWaterMark) || null,
  highWaterMark: undefined || null,
  highWaterMark: null,

或者:

// options starts out as an object
  highWaterMark: options && options.highWaterMark || null,
// equivalent to
  highWaterMark: (options && options.highWaterMark) || null,
  highWaterMark: (options.highWaterMark) || null,
  highWaterMark: options.highWaterMark,

那么,代码的作用就是

  • 检查 options 变量是否为真

  • 如果是,则将optionshighWaterMark属性赋给对象[=39]的highWaterMark属性 =]

  • 否则,它将null分配给那个属性

等同于:

let highWaterMark;
if (options) {
  highWaterMark = options.highWaterMark;
} else {
  highWaterMark = null;
}
const stream = new PassThrough({ highWaterMark });

这允许 createStream 的调用者是以下类型之一:

createStream();

createStream({ highWaterMark: 'foo' });