使用 CoffeeScript 检查对象中是否存在键的最简单方法

在 CoffeeScript 中,检查对象中是否存在键的最简单方法是什么?

60471 次浏览
obj.hasOwnProperty(name)

(to ignore inherited properties)

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.)

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.

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