简体   繁体   中英

Javascript - Check if key exists in object

I'm building a object in Javascript to parse the uri contents and attach their key / value pairs to it. However, I'm stuck on how to find out if a key exists. Here's the code :

var uri = {
    segments : {},
    parse : function() {
        var segments = {};
        var parts;
        var s;

        parts = location.href.split('/');
        parts = parts[3].split('?');
        parts = parts[1].split('&');

        for (var i = 0; i < parts.length; i++) {
            s = parts[i].split('=');
            segments[s[0]] = s[1];
        }

        uri.segments = segments;

        return segments;
    },
    segment : function(key) {
        if (uri.segments.length == 0)
        {
            uri.parse();
        }

        /* before was 'key in uri-segments' */      
        if (Object.prototype.hasOwnProperty.call(uri.segments, key))
        {
            return uri.segments[key];
        }
        else
        {
            return false
        }
    },
};

edit : full code

Use the hasOwnProperty method to check whether a key exists or not:

// hasOwnProperty from the objects prototype, to avoid conflicts
Object.prototype.hasOwnProperty.call(uri.segments, key);
//                                   ^ object      ^ key

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM