繁体   English   中英

else 语句不重新调整值

[英]else statement not retuning values

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

我想返回{brand: 'unknown', locale: {country: '', language: ''}, ENV: '', accessPath: '', contrastPreference: '' }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"进行比较。

我还会移动该检查,以便具有类似标志名称( 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']不是其他一些虚假值,但它看起来像是一个安全的假设。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM