在JS中如何简写使变量赋值为0当属性为空

ChatGPT4o 使用 ChatGPT 4o 回答

问题:

在js中使用var t = $(this).attr("yh");赋予变量时,如果$(this).attr("yh");属性为空,如何简写使得变量赋予为0

回答:

在JavaScript中,你可以使用逻辑或运算符 (||) 来简写这种情况。如果 $(this).attr("yh") 返回 nullundefined,你可以让变量 t 赋值为 0。具体代码如下:

var t = $(this).attr("yh") || 0;

这个表达式的意思是,如果 $(this).attr("yh") 的值是 nullundefined、空字符串 ("")、0NaNfalse,那么 t 将被赋值为 0。否则,t 将被赋值为 $(this).attr("yh") 的值。

如果你只想在属性值为 nullundefined 时赋值为 0,而保留其他假值(如空字符串、0 等),你可以使用三元运算符来实现:

var t = $(this).attr("yh");
t = (t === null || t === undefined) ? 0 : t;

这样,只有在 $(this).attr("yh") 返回 nullundefined 时,t 才会被赋值为 0