喵-见缝插针 2011-04-01 15:14 采纳率: 0%
浏览 492
已采纳

在 JavaScript 中是否有一个标准函数来检查空值、未定义或空白变量?

Is there a universal JavaScript function that checks that a variable has a value and ensures that it's not undefined or null? I've got this code, but I'm not sure if it covers all cases:

function isEmpty(val){
    return (val === undefined || val == null || val.length <= 0) ? true : false;
}

转载于:https://stackoverflow.com/questions/5515310/is-there-a-standard-function-to-check-for-null-undefined-or-blank-variables-in

  • 写回答

29条回答 默认 最新

  • from.. 2011-04-01 15:17
    关注

    You can just check if the variable has a truthy value or not. That means

    if( value ) {
    }
    

    will evaluate to true if value is not:

    • null
    • undefined
    • NaN
    • empty string ("")
    • 0
    • false

    The above list represents all possible falsy values in ECMA-/Javascript. Find it in the specification at the ToBoolean section.

    Furthermore, if you do not know whether a variable exists (that means, if it was declared) you should check with the typeof operator. For instance

    if( typeof foo !== 'undefined' ) {
        // foo could get resolved and it's defined
    }
    

    If you can be sure that a variable is declared at least, you should directly check if it has a truthy value like shown above.

    Further read: http://typeofnan.blogspot.com/2011/01/typeof-is-fast.html

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(28条)

报告相同问题?

悬赏问题

  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题