我在Javascript中构建一个对象来解析uri内容并将它们的键/值对附加到它。但是,我仍然坚持如何找出密钥是否存在。这是代码:
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
}
},
};
修改:完整代码
答案 0 :(得分:7)
使用hasOwnProperty
方法检查密钥是否存在:
// hasOwnProperty from the objects prototype, to avoid conflicts
Object.prototype.hasOwnProperty.call(uri.segments, key);
// ^ object ^ key