ajs*_*sie 109 javascript coffeescript
在CoffeeScript中,检查对象中是否存在密钥的最简单方法是什么?
Tre*_*ham 181
key of obj
Run Code Online (Sandbox Code Playgroud)
这适用于JavaScript key in obj.(CoffeeScript of在引用键in时使用,在引用数组值时:val in arr将测试是否val在arr.)
如果你想忽略对象的原型,那么你的答案是正确的.如果你想忽略带有null或者undefined值的键,Jimmy的答案是正确的.
lim*_*der 34
'?' 操作员检查是否存在:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
57334 次 |
| 最近记录: |