Answers:
key of obj
这将编译为JavaScript的key in obj。(of当引用键和in引用数组值时,CoffeeScript会使用:val in arr将测试是否val在中arr。)
如果您想忽略对象的原型,thejh的答案是正确的。如果要忽略带有null或undefined值的键,吉米的答案是正确的。
'?' 操作员检查是否存在:
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?可能是最简洁的。
obj.hasOwnProperty(name)
(忽略继承的属性)
key of obj如果值是字符串或数字,将引发错误。Cannot use 'in' operator to search。在这种情况下,如果对象不是未定义且不为null,它将起作用。
own key of obj附加测试也很有可能.hasOwnProperty()。“最有可能”来自我没有尝试过的方法,但是这种语法可以理解。