gpt4 book ai didi

Javascript - 用 0 替换未定义

转载 作者:行者123 更新时间:2023-12-03 12:36:27 26 4
gpt4 key购买 nike

我有一个由用户输入定义的变量。我只想替换它的值 undefined .但如果是 NaN 则不是.我该怎么做?
我试着做 x || 0但这也取代了NaN值(value)观。

最佳答案

您可以与 undefined 进行严格比较值(value)。

if (x === undefined) {
x = 0;
}

自然你会想要确定 x已像往常一样正确声明。

如果您对 undefined 有任何敏感性值被非常糟糕的代码所困扰(被新值覆盖),那么您可以使用 void运营商获得保证 undefined .您可以与 undefined进行严格比较值(value)。
if (x === void 0) {
x = 0;
}
void 的操作数没关系。不管你给它什么,它都会返回 undefined .

这些都是等价的:
if (x === void undefined) {
x = 0;
}

if (x === void "foobar") {
x = 0;
}

if (x === void x) {
x = 0;
}

最终如果有人压扁了 undefined在本地(它不能再被全局压缩),最好修复那个坏代码。

如果您想同时检查 nullundefined同时,只有那些值,你可以使用 ==而不是 === .
if (x == null) {
x = 0;
}

现在 x将设置为 0如果是 nullundefined ,但没有任何其他值。您可以使用 undefined在测试中。完全一样。
if (x == undefined) {
x = 0;
}

从您的问题来看,您似乎在专门寻找 number元素,甚至 NaN .如果您想将其限制为原始数字,包括 NaN ,然后使用 typeof为测试。
if (typeof x !== "number") {
x = 0;
}

但是,您将丢失可以成功转换为数字的数字字符串和其他值,因此这取决于您最终需要什么。

关于Javascript - 用 0 替换未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27320166/

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