[英]Javascript - Check if key exists in object
我正在用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
}
},
};
編輯 :完整代碼
使用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.