英文:
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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论