else 语句不返回值

else statement not retuning values

在我的代码中,我正在检查 windowwindow['cid_global'] 是否有任何一个未定义,

我想 return {品牌:'unknown',语言环境:{国家:'',语言:''},环境:'',访问路径:'' , contrastPreference: '' }cid_global.

但它 return 是 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 进行比较。您需要将其与 string "undefined".

进行比较

我还会移动该检查,以便名称为 flag-like 的变量(isClientisCidGlobal)实际上是标志,而不是字符串。此外,如果 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'] 不是其他虚假值,但它看起来是一个安全的假设。)