[英]How do you make an JavaScript object's properties enumerable?
我有一個類型為ServiceWorkerRegistration
的 object,我想對其進行字符串化:
const reg = await navigator.serviceWorker.register(`https://www.myurl.com/Worker.js`, {scope:"/"});
當我console.log(reg)
我得到以下信息:
ServiceWorkerRegistration { installing: null, waiting: null, active: ServiceWorker, navigationPreload: NavigationPreloadManager, scope: "https://www.myurl.com/", updateViaCache: "imports", onupdatefound: null, pushManager: PushManager }
active: ServiceWorker { scriptURL: "https://www.myurl.com/Worker.js", state: "activated", onstatechange: null, … }
onerror: null
onstatechange: null
scriptURL: "https://www.myurl.com/Worker.js"
state: "activated"
<prototype>: ServiceWorkerPrototype { postMessage: postMessage(), scriptURL: Getter, state: Getter, … }
installing: null
navigationPreload: NavigationPreloadManager { }
onupdatefound: null
pushManager: PushManager { }
scope: "https://www.myurl.com/"
updateViaCache: "imports"
waiting: null
<prototype>: ServiceWorkerRegistrationPrototype { update: update(), unregister: unregister(), showNotification: showNotification(), … }
當我執行typeof reg
時,我得到'object'
但是,如果我嘗試JSON.stringify(reg)
我會得到{}
。 同樣,如果我嘗試執行Object.keys(reg)
我會得到[]
。
我查看了諸如Why does JSON.stringify return empty object notation "{}" for an object that seems to have properties 這樣的答案? 為什么 JSON.stringify 在 TypeError 上返回一個空的 object ,它聲稱當 object 沒有可枚舉的屬性時會發生這種情況。
創可貼解決方案是我手動打印每個字段,例如console.log(reg["installing"]);
,或手動將每個屬性重置為可枚舉的屬性,例如Object.defineProperty(reg, 'installing', {enumerable: true})
每個屬性。
但是我希望能夠做類似的事情:
Object.keys(reg).forEach(key=>console.log(reg[key]));
為此,object 必須具有可枚舉屬性。 如何使屬性可枚舉?
根據評論,我的工作解決方案是復制 object(TS 中的解決方案):
const objCpy = (obj : any) : string =>{
let newObj : any = {}
const keys : string[] = Object.keys(Object.getPrototypeOf(obj));
keys.forEach((key : string)=>{
let val : any = obj[key]
if(typeof val === "object" && val !== null){
val = objCpy(val)
}
newObj[key] = val;
})
return newObj;
}
然后按預期進行字符串化:
JSON.stringify(objCpy(reg))
>> `{"installing":{"scriptURL":"http://localhost:3001/Worker.js","state":"installing","onstatechange":null,"onerror":null},"waiting":null,"active":null,"navigationPreload":{},"scope":"http://localhost:3001/","updateViaCache":"imports","onupdatefound":null,"pushManager":{}}`
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.