在CoffeeScript中,检查对象中是否存在键的最简单方法是什么?
key of obj
这段代码编译成JavaScript后变为 key in obj
。 (CoffeeScript 引用键时使用 of
,引用数组值时使用 in
: val in arr
将测试 val
是否在 arr
中。)
如果要忽略对象的原型,则 thejh 的答案是正确的。如果要忽略具有null
或undefined
值的键,则 Jimmy 的答案是正确的。
'?'运算符用于检查其后面的内容是否存在:
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
,则此操作将失败。 - mu is too shortobj.key?
可能是最简洁的写法。 - Andrew Maoobj.hasOwnProperty(name)
忽略继承的属性key of obj
会抛出错误。在这种情况下,如果对象不是未定义的并且不是空的,它将起作用。 - jqualls
obj
的自有键也可以用来测试.hasOwnProperty()
。我说“很可能”是因为我没有尝试过,但这种语法在推导中是有效的。 - flying sheepown = (prop, obj) -> Object::hasOwnProperty.call obj, prop
- flying sheep