gpt4 book ai didi

javascript - 使用(变量类型)作为条件是否不正确? es-lint 显示意外的恒定条件

转载 作者:行者123 更新时间:2023-12-02 23:11:01 25 4
gpt4 key购买 nike

我正在 Javascript 中设置一个 Rest api,需要检查参数是否为 bool 值。我可以使用 JSON.parse(variable)=='boolean' 来完成此操作,但这会导致 eslint 错误(无恒定条件)。我可以禁用此行的错误,但我很好奇是否有理由不这样做。

我已阅读该错误的文档。

A constant expression (for example, a literal) as a test condition might be a typo or development trigger for a specific behavior. For example, the following code looks as if it is not ready for production.

https://eslint.org/docs/rules/no-constant-condition

据我所知,忽略它似乎是可以的。

try {
if (!typeof JSON.parse(x) === 'boolean') {
throw new Error('x must be boolean');
}
} catch (e) {
throw new Error('x must be boolean');
}

最佳答案

no-constant-condition 规则按预期工作。您的 if 语句的计算结果始终为 false。我会分解解释

  1. typeof JSON.parse(x) 将返回 (string, number, boolean 类型的字符串> 等)
  2. !SOMETHING总是返回一个 bool 值
    1. 如果 SOMETHINGfalsy,则 !SOMETHING 将为 true(非 false em>)
    2. 如果 SOMETHINGtrue,则 !SOMETHING 将为 false(不是 true em>)

这意味着您正在将 boolean(类型)与 string(类型)与 === 进行比较。要修复您的场景,您需要将 ! (不是)移至评估器

try {
if (typeof JSON.parse(x) !== 'boolean') {
throw new Error('x must be boolean');
}
} catch (e) {
throw new Error('x must be boolean');
}

关于javascript - 使用(变量类型)作为条件是否不正确? es-lint 显示意外的恒定条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57362162/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com