jlg*_*all 8 javascript cross-browser for-in-loop hasownproperty
在某些浏览器(Chrome,Safari浏览器),Object.keys()不返回所有的按键时for-in循环与hasOwnProperty()回报.
有没有使用for-in循环的解决方法?
还有另一个对象,window它表现出同样的错误,或者只是window对象的问题,因为我的测试往往显示?
两者都应该只返回自己的和只有可枚举的属性,因为我们可以从文档中读取:
hasOwnProperty():" 一种用于... in循环只遍历枚举.性能 "和hasOwnProperty()过滤掉原型链继承属性,保持只在自己的属性.Object.keys():" 将返回其可枚举自身属性的对象. "结论:他们应该迭代相同的键:只有可枚举和自己的属性.
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"]
Run Code Online (Sandbox Code Playgroud)
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"]
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)