Checking if a key exists in a JavaScript object?

2018-12-31 04:04发布

How do I check if a particular key exists in a JavaScript object or array?

If a key doesn't exist, and I try to access it, will it return false? Or throw an error?

19条回答
何处买醉
2楼-- · 2018-12-31 04:32

If you are using underscore.js library then object/array operations become simple.

In your case _.has method can be used. Example:

yourArray = {age: "10"}

_.has(yourArray, "age")

returns true

But,

_.has(yourArray, "invalidKey")

returns false

查看更多
登录 后发表回答