【问题标题】:Simplest way to check if key exists in object using CoffeeScript使用 CoffeeScript 检查对象中是否存在键的最简单方法
【发布时间】:2012-01-04 19:00:26
【问题描述】:

在 CoffeeScript 中,检查对象中是否存在键的最简单方法是什么?

【问题讨论】:

    标签: javascript coffeescript


    【解决方案1】:
    obj.hasOwnProperty(name)
    

    (忽略继承的属性)

    【讨论】:

    • 我喜欢这个响应,因为如果值是字符串或数字,key of obj 会抛出错误。 Cannot use 'in' operator to search。在这种情况下,如果对象不是 undefined 且不是 null,它将起作用。
    • 如果对象具有其原型中的值,则此操作失败。
    【解决方案2】:
    key of obj
    

    这编译为 JavaScript 的 key in obj。 (CoffeeScript 引用键时使用of,引用数组值时使用inval in arr 将测试val 是否在arr 中。)

    如果您想忽略对象的原型,thejh 的答案是正确的。如果您想忽略具有nullundefined 值的键,Jimmy 的回答是正确的。

    【讨论】:

    • 很可能own key of obj 也可以用于额外测试.hasOwnProperty()。 “最有可能”来自我没有尝试过,但这种语法在理解中起作用。
    • @flyingsheep 不,它只适用于理解。试试看:coffeescript.org/#try:own%20key%20of%20obj
    • 啊,okown = (prop, obj) -> Object::hasOwnProperty.call obj, prop
    【解决方案3】:

    “?”操作员检查是否存在:

    if obj?
        # object is not undefined or null
    
    if obj.key?
        # obj.key is not undefined or null
    
    # call function if it exists
    obj.funcKey?()
    
    # chain existence checks, returns undefined if failure at any level
    grandChildVal = obj.key?.childKey?.grandChildKey
    
    # chain existence checks with function, returns undefined if failure at any level
    grandChildVal = obj.key?.childKey?().grandChildKey
    

    【讨论】:

    • 如果密钥存在但值为null,则会失败。
    • 在不关心密钥存在但为空的情况下,obj.key? 可能是最简洁的。
    猜你喜欢
    • 2012-10-27
    • 1970-01-01
    • 2011-09-14
    • 2011-05-24
    • 1970-01-01
    • 2013-09-26
    • 2013-01-04
    • 1970-01-01
    • 2021-11-25
    相关资源
    最近更新 更多