首页 > 解决方案 > ConditionalExpression 中的意外赋值

问题描述

我正在尝试更新从 GitHub 获得的库,并且有一个我以前从未见过的奇怪情况,有人可以帮我理解这是什么吗?据我了解_c = _b === null,这意味着 _c get 的值是 true 或 false ......后来 _c !== undefined 将永远是 true ..我错过了什么吗?

  const _b = { isWrappable: true, insertedTag: false };
  let _c;
  const status = (_c = _b === null || _b === undefined ? undefined : _b.isWrappable) !== null && _c !== undefined ? _c : false;
  console.log(status);

status在这条线之后true

现在,我怎样才能改变这条线以避免Unexpected assignment within ConditionalExpression.因为我尝试的一切都给了我false,例如:

  const _b = { isWrappable: true, insertedTag: false };
  const _c = _b === null;
  const test = (_c || _b === undefined ? undefined : _b.isWrappable) !== null && _c !== undefined ? _c : false;
  console.log(test);

谢谢

标签: javascript

解决方案


我已经解决了:) 在我的研究中我发现了 Nullish 合并运算符 (??) 并解决了我的问题所以答案是

const _b = {
  isWrappable: true,
  insertedTag: false
};
const status = _b?.isWrappable ?? false;
console.log(status);

可选的链式操作符和 Nullish 合并操作符解决了这个问题。


推荐阅读