在某些浏览器(Chrome,Safari)中,Object.keys()
无法返回for-in loop hasOwnProperty()
返回的所有密钥。
是否有不使用for-in循环的解决方法?
还有另一个对象而不是window
表现出相同的错误,或者只是window
对象的问题,因为我的测试往往显示?
两者都应该返回仅拥有且只有可枚举的属性,我们可以从文档中读取:
hasOwnProperty()
:"A for...in loop only iterates over enumerable properties."和hasOwnProperty()
过滤掉原型链中的继承属性,只保留 拥有 properties。Object.keys()
:"The object whose enumerable own properties are to be returned." 结论:他们应该迭代相同的键:可枚举和拥有属性。
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);