[英]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. 我正在用Javascript构建一个对象,以解析uri内容并将其键/值对附加到它。 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
方法检查密钥是否存在:
// hasOwnProperty from the objects prototype, to avoid conflicts
Object.prototype.hasOwnProperty.call(uri.segments, key);
// ^ object ^ key
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.