在js中使用var t = $(this).attr("yh");赋予变量时,如果$(this).attr("yh");属性为空,如何简写使得变量赋予为0
在JavaScript中,你可以使用逻辑或运算符 (||
) 来简写这种情况。如果 $(this).attr("yh")
返回 null
或 undefined
,你可以让变量 t
赋值为 0
。具体代码如下:
var t = $(this).attr("yh") || 0;
这个表达式的意思是,如果 $(this).attr("yh")
的值是 null
、undefined
、空字符串 (""
)、0
、NaN
或 false
,那么 t
将被赋值为 0
。否则,t
将被赋值为 $(this).attr("yh")
的值。
如果你只想在属性值为 null
或 undefined
时赋值为 0
,而保留其他假值(如空字符串、0
等),你可以使用三元运算符来实现:
var t = $(this).attr("yh");
t = (t === null || t === undefined) ? 0 : t;
这样,只有在 $(this).attr("yh")
返回 null
或 undefined
时,t
才会被赋值为 0
。