• Javascript 对象值与null undefined和空字符串


    if (value) 是否足以判断一个值存在且不为空字符串?

    答案是 是的。


    if ((fields === null) || (fields === undefined) || (fields.length === 0)) {
     ...                    
    }

    if( value ) {
    }
    是等价的。


    备注1:

    if( value ) {
    }

    will evaluate to true if value is not:

    • null
    • undefined
    • NaN
    • empty string ("")
    • 0
    • false
    备注2:

    1. For objects, accessing a property that hasn't been attached will return undefined. You might see an error raised if you try to do something with it, like calling it as a method, but just accessing it is usually fine as long as the object itself exists. [2]
    2. Since accessing a property that doesn't exist and a property with value undefinedgives you the same result, using the typeof or equality operators is not enough to tell undefined properties apart from nonexistent ones. For that we can use in, which returns true if the object has the property and false if it doesn't, or Object.hasOwnProperty(), which does the same thing but doesn't look in the prototype chain.
    备注说明,对象中的成员,可以直接用来访问,不用事先判断是否存在(但是对象要先存在)


    摘自:
    http://stackoverflow.com/questions/5515310/is-there-a-standard-function-to-check-for-null-undefined-or-blank-variables-in
    https://www.quora.com/What-is-the-best-way-to-check-if-a-property-or-variable-is-undefined

  • 相关阅读:
    最简单的UDP程序
    最简单的TCP程序
    一道面试题的分析
    JDK5新特性:可变参数方法
    文件IO流总结
    集合使用的总结
    双列集合Map的嵌套遍历
    集合HashSet的使用
    集合TreeSet的使用
    用LinkedList模拟Stack功能
  • 原文地址:https://www.cnblogs.com/mosakashaka/p/12534667.html
Copyright © 2020-2023  润新知