且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

速记功能用于检查属性是否存在

更新时间:2023-11-27 19:11:10

Here's a function I have lying around from a project that tells you if a property is defined (including all of its parent properties, if any):

function isDefined(target, path) {
    if (typeof target != 'object' || target == null) {
        return false;
    }

    var parts = path.split('.');

    while(parts.length) {
        var branch = parts.shift();
        if (!(branch in target)) {
            return false;
        }

        target = target[branch];
    }

    return true;
}

It's supposed to be used like this:

var data = { foo: { bar: 42 } };
isDefined(data, "foo"); // true
isDefined(data, "foo.bar"); // true
isDefined(data, "notfoo"); // false
isDefined(data, "foo.baz"); // false

You can easily tweak this to return the value itself (or null) instead of true/false.

Update: After reading the comments on the question, I googled the Javascript in operator and replaced the typeof test with that. Now the code is written "how it was meant to be".

相关阅读

推荐文章