使用CoffeeScript检查对象中是否存在键的最简单方法


Answers:


182
key of obj

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

如果您想忽略对象的原型,thejh的答案是正确的。如果要忽略带有null或undefined值的键,吉米的答案是正确的。


2
own key of obj附加测试也很有可能.hasOwnProperty()。“最有可能”来自我没有尝试过的方法,但是这种语法可以理解。
— 飞羊

2
@flyingsheep不,它只能在理解方面起作用。尝试:coffeescript.org/#try
— Trevor Burnham

啊,好的:own = (prop, obj) -> Object::hasOwnProperty.call obj, prop
— 飞羊

36

'?' 操作员检查是否存在:

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

16
如果键在那里但值为,则失败null。
— 亩太短了

在一个人不关心存在但为空的键的情况下,那obj.key?可能是最简洁的。
— 安德鲁·毛

21
obj.hasOwnProperty(name)

(忽略继承的属性)


我喜欢此响应,因为key of obj如果值是字符串或数字,将引发错误。Cannot use 'in' operator to search。在这种情况下,如果对象不是未定义且不为null,它将起作用。
— jqualls 2014年

如果对象具有其原型的值,则此操作将失败。
— 布赖恩·亨特
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.