JavaScript 将 NULL 转换为 0 [英] JavaScript convert NULL to 0

查看:125
本文介绍了JavaScript 将 NULL 转换为 0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 jQuery 来获取元素的高度.但是如果元素不存在,下面的代码将返回NULL:

I'm using jQuery to get the height of an element. But if the element doesn't exist, the following code will return NULL:

$height = $('#menu li.active ul').height(); // returns integer or null

在每种情况下使用以下代码获取整数值是否是一种跨浏览器安全的方法:

Is it a cross-browser safe way for getting an integer value under every circumstance with the following code:

$height = $('#menu li.active ul').height() + 0;

推荐答案

有很多方法可以解决这个问题.您描述的那个,添加一个整数值来强制类型很好.您也可以显式转换为数字:

There are many ways to deal with this. The one you describe, adding an integer value to coerce the type is fine. You could also convert to a number explicitly:

$height = Number($('#menu li.active ul').height());
// or:
$height = +$('#menu li.active ul').height();

或者您可以使用逻辑运算符作为 null 强制为 false:

Or you could use a logical operator as null coerces to false:

$height = $('#menu li.active ul').height() || 0;

这篇关于JavaScript 将 NULL 转换为 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆