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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:17:53  来源:igfitidea点击:

Simplest way to check if key exists in object using CoffeeScript

javascriptcoffeescript

提问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 ofwhen referring to keys, and inwhen referring to array values: val in arrwill test whether valis in arr.)

这将编译为 JavaScript 的key in obj. (CoffeeScriptof在引用键和in引用数组值时使用:val in arr将测试是否valarr.)

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 nullor undefinedvalue.

如果你想忽略对象的原型,thejh 的答案是正确的。如果您想忽略带有 anullundefined值的键,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)

(忽略继承的属性)