在我的代码,我检查window
和window['cid_global']
如果他们中的任何一个不确定的,
我想将{brand:'unknown',locale:{country:``,language:''},ENV:'',accessPath:'',对比度首选项:''}返回给cid_global
。
但它返回为undefined
。
我在这里做错了什么?
stackBliz:https ://stackblitz.com/edit/typescript-7d1urh
const isClient = typeof window;
const isCidGlobal = typeof window['cid_global'];
const _window = isClient !== undefined ? window : {};
const cid_global = (_window !== undefined && isCidGlobal !== undefined)? _window['cid_global'] : {brand: 'unknown', locale: {country: '', language: ''}, ENV: '', accessPath: '', contrastPreference: '' };
console.log(isCidGlobal) // undefined;
console.log(cid_global) // should return object instead of undefined;
typeof
结果是一个字符串。您正在将其与值进行比较undefined
。您需要将其与字符串 进行比较"undefined"
。
我还谨检查,以便您的变量与标志般的名字(isClient
,isCidGlobal
)实际上是标志,而不是字符串。另外,如果window
未定义,则第二行将失败,因为您尝试使用undefined['cid_global']
。
因此,例如:
const isClient = typeof window !== "undefined";
// *** −−−−−−−−−−−−−−−−−−−−−−−−−−−−^−−−−−−−−−^
const isCidGlobal = isClient && typeof window['cid_global'] !== "undefined";
// *** −−−−−−−−−−−−−^^^^^^^^^^^^−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^
const _window = isClient ? window : {}; // ** Removed the comparison
// *** Replaced everything before the ? with just `isCidGlobal`
const cid_global = isCidGlobal ? _window['cid_global'] : {brand: 'unknown', locale: {country: '', language: ''}, ENV: '', accessPath: '', contrastPreference: '' };
但是除非您将其用于其他用途,否则您不需要_window
:
const isClient = typeof window !== "undefined";
const isCidGlobal = isClient && typeof window['cid_global'] !== "undefined";
const cid_global = isCidGlobal ? window['cid_global'] : {brand: 'unknown', locale: {country: '', language: ''}, ENV: '', accessPath: '', contrastPreference: '' };
或者,除非您将其用于其他用途,否则isCidGlobal
:
const isClient = typeof window !== "undefined";
const isCidGlobal = (isClient && window['cid_global']) || {brand: 'unknown', locale: {country: '', language: ''}, ENV: '', accessPath: '', contrastPreference: '' };
(当然,该版本假设window['cid_global']
不是其他虚假的值,但看起来像是一个安全的假设。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句