我有一个ServiceWorkerRegistration
类型的对象,我想将其字符串化:
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?和Why does JSON.stringify on TypeError return an empty object这样的答案,它们声称当对象没有可枚举属性时会发生这种情况。
一个权宜之计是手动打印每个字段,例如console.log(reg["installing"]);
,或者手动将每个属性重置为可枚举的,例如每个属性的Object.defineProperty(reg, 'installing', {enumerable: true})
。
但是,我希望能够执行以下操作:
Object.keys(reg).forEach(key=>console.log(reg[key]));
要做到这一点,对象必须有可枚举的属性。我如何使属性可枚举?
1条答案
按热度按时间nimxete21#
根据评论,我的工作解决方案是只制作对象的副本(TS中的解决方案):
然后它如预期的那样字符串化: