Checking if a key exists in a JavaScript object?

前端 未结 22 2267
礼貌的吻别
礼貌的吻别 2020-11-21 22:57

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?<

22条回答
  •  自闭症患者
    2020-11-21 23:40

    Here's a helper function I find quite useful

    This keyExists(key, search) can be used to easily lookup a key within objects or arrays!

    Just pass it the key you want to find, and search obj (the object or array) you want to find it in.

    function keyExists(key, search) {
            if (!search || (search.constructor !== Array && search.constructor !== Object)) {
                return false;
            }
            for (var i = 0; i < search.length; i++) {
                if (search[i] === key) {
                    return true;
                }
            }
            return key in search;
        }
    
    // How to use it:
    // Searching for keys in Arrays
    console.log(keyExists('apple', ['apple', 'banana', 'orange'])); // true
    console.log(keyExists('fruit', ['apple', 'banana', 'orange'])); // false
    
    // Searching for keys in Objects
    console.log(keyExists('age', {'name': 'Bill', 'age': 29 })); // true
    console.log(keyExists('title', {'name': 'Jason', 'age': 29 })); // false

    It's been pretty reliable and works well cross-browser.

提交回复
热议问题