How to fix: Unsafe arithmetic operation on optional chaining. It can result in NaN eslint error?

huangapple go评论106阅读模式
英文:

How to fix: Unsafe arithmetic operation on optional chaining. It can result in NaN eslint error?

问题

在我的代码中,我需要检查此对象,它返回一个 HTML 元素,并检查其 className 是否等于 "is-visible"。但是出现了 eslint 错误。我尝试过添加条件链,但这并不起作用。

const objVisible = (obj) =>
    obj.Components.Elements.slides[0].classList.contains("is-visible") &&
    obj.Components.Elements.slides[tags?.length - 1].classList.contains("is-visible");
const objVisible = (obj) =>
    obj?.Components?.Elements?.slides[0]?.classList.contains("is-visible") &&
    obj?.Components?.Elements?.slides[tags?.length - 1]?.classList.contains("is-visible");
英文:

In my code, i need to check if this object, which returns and html Element and check if a className equal to "is-visible". But this eslint error is popping up. Ive tried adding conditional chaining but that isn't working.

  const objVisible = (obj) =>
    obj.Components.Elements.slides[0].classList.contains("is-visible") &&
    obj.Components.Elements.slides[tags?.length - 1].classList.contains(
      "is-visible"
    );
  const objVisible = (obj) =>
    obj?.Components?.Elements?.slides[0]?.classList.contains("is-visible") &&
    obj?.Components?.Elements?.slides[tags?.length - 1]?.classList.contains(
      "is-visible"
    );

答案1

得分: 0

我认为问题出在
tags?.length - 1
如果 tags 未设置,这将解析为
undefined - 1
这被 eslint 视为一个"不安全的算术操作",理所当然。

很难说如何修复它,不知道你的 tags 具体是做什么的。可能的解决方法是:

const objVisible = (obj) =>
  obj.Components.Elements.slides[0].classList.contains("is-visible") &&
  tags && obj.Components.Elements.slides[tags?.length - 1].classList.contains(
    "is-visible"
  );
英文:

I think the problem is

tags?.length - 1

If tags is not set, this resolves to

undefined - 1

which eslint considers an "unsafe arithmetic operation", rightly so.

Hard to say how to fix it without knowing what your tags do though. Probably:

 const objVisible = (obj) =>
    obj.Components.Elements.slides[0].classList.contains("is-visible") &&
    tags && obj.Components.Elements.slides[tags?.length - 1].classList.contains(
      "is-visible"
    );
 

</details>



huangapple
  • 本文由 发表于 2023年2月24日 07:31:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/75551333.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定