【问题标题】:Not understanding logical operators in a specific situation不理解特定情况下的逻辑运算符
【发布时间】:2020-02-17 02:02:37
【问题描述】:

我正在查看另一个人的代码,发现这个特定部分我不明白逻辑运算符的用途。 (请注意,我仍然从 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() 语句中使用逻辑运算符,但这对我来说没有意义,而且我在网上找不到很多解释。

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

【问题讨论】:

  • 这能回答你的问题吗? The logical && and || operators in JavaScript
  • 这意味着,如果 options.highWaterMark 没有值,则将 options.highWaterMark 的值设置为 null。这样做可以避免未定义的变量产生意想不到的影响。此外,可以在脚本的其他地方检查 options.highWaterMark 的空值,以确定是显示还是隐藏文档中的某些相关元素。这意味着您只需要检查 null,而不是 null 或 undefined。

标签: javascript node.js stream logical-operators


【解决方案1】:

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

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

等价于

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

另外,请记住&& 如果左侧是假的,则解析到左侧,否则解析到右侧。所以如果options 是undefined,(options && options.highWaterMark) 会解析为undefined。

那里需要&&,因为如果options 参数不存在(例如undefined 或null),只需这样做

highWaterMark: options.highWaterMark || null,

会抛出错误,因为您无法访问 undefined 或 null 的属性。

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

// 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 变量是否为真

  • 如果是这样,它会将options 的highWaterMark 属性分配给对象的highWaterMark 属性

  • 否则,它会将null 分配给该属性

相当于如下:

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

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

createStream();

或

createStream({ highWaterMark: 'foo' });

【讨论】:

  • 非常感谢!我的大脑在那里融化了一秒钟,试图理解你所说的,但在分析了你发给我的页面并试图理解之后,我终于明白了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-20
  • 1970-01-01
  • 1970-01-01
  • 2013-09-06
相关资源
最近更新 更多