gpt4 book ai didi

javascript - 函数中未定义或空变量

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

在这些示例中,我正在破坏带有条件的函数;

function validPrice(price)
{
if(price=="" || price==0 || price==null || price==undefined )
{
//do something
}
else
{
// do something different
}
}
var priceNew = $("li#listedProd").attr("price");

validPrice(priceNew);

我的问题是这些条件有什么不同price==""||价格==0 ||价格==空||价格==未定义

最佳答案

第一个编写该代码的人是

a) 对 future 的使用非常防御。b) 不明白 attr 是如何工作的。

方法attr(或getAttribute的底层调用将返回

  • 找到属性的字符串值
  • null,如果不是。

重要的是,如果有一个 0 值,它将是一个字符串 0 ,因此不会被捕获下面的测试 - 针对price == 0测试,因为系统会自动将其转换为数字作为==比较的一部分。

if(price=="" || price==0 || price==null || price==undefined )

而且,由于转换的内部工作方式,这些测试无法按预期工作。 ===== 是不同的。应该是:

if(price === "" || price === 0 || price === null || price === undefined )

所有这些都可以很容易地简化为简单的“价格”,因为如何如何coercion to boolean work :

if (!price) 

或者,如果您想捕获“0”

if (!price || +price === 0)

(+price 强制价格为数字,因此我们捕获 0 0.00 和其他变体。)

关于javascript - 函数中未定义或空变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25343149/

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