【问题标题】:else statement not retuning valueselse 语句不返回值
【发布时间】:2020-12-08 13:39:11
【问题描述】:

在我的代码中,我正在检查 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;

【问题讨论】:

    标签: javascript typescript conditional-operator


    【解决方案1】:

    typeof 的结果是一个字符串。您将它与值undefined 进行比较。您需要将其与 string "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'] 不是其他虚假值,但它看起来是一个安全的假设。)

    【讨论】:

    • 或者最终直接window['cid_global'] !== undefined
    • @Cid - 是的,一旦你知道window 存在,你就可以这样做。
    • 注意:有几个===s 应该是!==s。我现在已经修好了。
    猜你喜欢
    • 2014-01-29
    • 1970-01-01
    • 1970-01-01
    • 2021-08-31
    • 1970-01-01
    • 2018-09-21
    • 2016-08-14
    • 2014-12-19
    • 2023-02-21
    相关资源
    最近更新 更多