乱世@小熊 2011-04-01 15:14 采纳率: 25%
浏览 1126
已采纳

是否有一个标准函数来检查 JavaScript 中的 null、 undefined 或空白变量?

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条回答 默认 最新

  • 北城已荒凉 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 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件