Javascript 使用 CoffeeScript 检查对象中是否存在键的最简单方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8242984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simplest way to check if key exists in object using CoffeeScript
提问by ajsie
In CoffeeScript, what is the simplest way to check if a key exists in an object?
在 CoffeeScript 中,检查对象中是否存在键的最简单方法是什么?
回答by Trevor Burnham
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
.)
这将编译为 JavaScript 的key in obj
. (CoffeeScriptof
在引用键和in
引用数组值时使用:val in arr
将测试是否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.
如果你想忽略对象的原型,thejh 的答案是正确的。如果您想忽略带有 anull
或undefined
值的键,Jimmy 的回答是正确的。
回答by limscoder
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
回答by thejh
obj.hasOwnProperty(name)
(to ignore inherited properties)
(忽略继承的属性)