如何修复Object.keys()中缺少的键与使用hasOwnProperty()的for ...相比较

时间:2015-07-17 10:04:01

标签: javascript cross-browser for-in-loop hasownproperty

在某些浏览器(Chrome,Safari)中,Object.keys()无法返回for-in loop hasOwnProperty()返回的所有密钥。

是否有不使用for-in循环的解决方法?

还有另一个对象而不是window表现出相同的错误,或者只是window对象的问题,因为我的测试往往显示?

澄清

两者都应该返回仅拥有且只有可枚举的属性,我们可以从文档中读取:

结论:他们应该迭代相同的键:可枚举拥有属性。

浏览器结果

1)Firefox 39:没有丢失密钥

2)Chromium 38:47缺少钥匙:

["speechSynthesis", "localStorage", "sessionStorage", "applicationCache", "webkitStorageInfo", "indexedDB", "webkitIndexedDB", "crypto", "CSS", "performance", "console", "devicePixelRatio", "styleMedia", "parent", "opener", "frames", "self", "defaultstatus", "defaultStatus", "status", "name", "length", "closed", "pageYOffset", "pageXOffset", "scrollY", "scrollX", "screenTop", "screenLeft", "screenY", "screenX", "innerWidth", "innerHeight", "outerWidth", "outerHeight", "offscreenBuffering", "frameElement", "clientInformation", "navigator", "toolbar", "statusbar", "scrollbars", "personalbar", "menubar", "locationbar", "history", "screen"]

3)Safari 5.1:缺少37个键:

["open", "moveBy", "find", "resizeTo", "clearTimeout", "btoa", "getComputedStyle", "setTimeout", "scrollBy", "print", "resizeBy", "atob", "openDatabase", "moveTo", "scroll", "confirm", "getMatchedCSSRules", "showModalDialog", "close", "clearInterval", "webkitConvertPointFromNodeToPage", "matchMedia", "prompt", "focus", "blur", "scrollTo", "removeEventListener", "postMessage", "setInterval", "getSelection", "alert", "stop", "webkitConvertPointFromPageToNode", "addEventListener", "dispatchEvent", "captureEvents", "releaseEvents"]

测试脚本

var res = (function(obj) {
    var hasOwn = Object.prototype.hasOwnProperty;

    var allKeys = [];
    for(var key in obj) {
        if(hasOwn.call(obj, key)) {
            allKeys.push(key);
        }
    }

    var keys = Object.keys(obj);

    var missingKeys = [];
    for(var i = 0; i < allKeys.length; i++) {
        if(keys.indexOf(allKeys[i]) === -1) {
            missingKeys.push(allKeys[i]);
        }
    }

    return {allKeys: allKeys, keys: keys, missingKeys: missingKeys};
})(window);

// This should be empty if the followings return the same set of keys:
// - for...in with hasOwnProperty()
// - Object.keys()
console.log(res.missingKeys, res.missingKeys.length);

0 个答案:

没有答案