In CoffeeScript, what is the simplest way to check if a key exists in an object?
在CoffeeScript中,检查对象中是否存在密钥的最简单方法是什么?
3 个解决方案
#1
176
key of obj
This compiles to JavaScript's key in obj
. (CoffeeScript uses of
when referring to keys, and in
when referring to array values: val in arr
will test whether val
is in arr
.)
这将编译为obj中的JavaScript键。 (CoffeeScript在引用键时使用,在引用数组值时:arr中的val将测试val是否在arr中。)
thejh's answer is correct if you want to ignore the object's prototype. Jimmy's answer is correct if you want to ignore keys with a null
or undefined
value.
如果你想忽略对象的原型,那么你的答案是正确的。如果要忽略具有null或未定义值的键,Jimmy的答案是正确的。
#2
32
The '?' operator checks for existence:
'?'操作员检查是否存在:
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
#3
20
obj.hasOwnProperty(name)
(to ignore inherited properties)
(忽略继承的属性)
#1
176
key of obj
This compiles to JavaScript's key in obj
. (CoffeeScript uses of
when referring to keys, and in
when referring to array values: val in arr
will test whether val
is in arr
.)
这将编译为obj中的JavaScript键。 (CoffeeScript在引用键时使用,在引用数组值时:arr中的val将测试val是否在arr中。)
thejh's answer is correct if you want to ignore the object's prototype. Jimmy's answer is correct if you want to ignore keys with a null
or undefined
value.
如果你想忽略对象的原型,那么你的答案是正确的。如果要忽略具有null或未定义值的键,Jimmy的答案是正确的。
#2
32
The '?' operator checks for existence:
'?'操作员检查是否存在:
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
#3
20
obj.hasOwnProperty(name)
(to ignore inherited properties)
(忽略继承的属性)