【问题标题】:Set boolean with default if options object does not exist如果选项对象不存在,则将布尔值设置为默认值
【发布时间】:2018-06-06 06:41:28
【问题描述】:

我想设置一个布尔值,我可以从选项对象的属性中获取,或者如果未定义,则想设置一个默认值。

const raw = options.rawOutput;

如果未设置 options.rawOutput,则默认值应为 true。 问题是:options 对象可能根本不存在。

我正在寻找比这样更优雅的解决方案

if (options) {
  if (options.rawOutput) {
    raw = rawOutput;
  }
} else {
   raw = true;
}

【问题讨论】:

    标签: javascript boolean javascript-objects


    【解决方案1】:

    您可以检查options 是否存在以及属性rawOutput 是否存在,然后取该值,否则取true

    raw = options && 'rawOutput' in options ? options.rawOutput : true;
    

    或相同但没有conditional (ternary) operator ?:

    raw = !options || !('rawOutput' in options) || options.rawOutput;
    

    【讨论】:

      【解决方案2】:

      我想使用 typeof 检查:

      const raw = ((typeof options == 'undefined') || (typeof options.rawOutput == 'undefined'))? true:options.rawOutput;
      

      【讨论】:

        【解决方案3】:

        利用 ES6 的力量:

        const { rawOptions: raw = true } = options || {};

        使用对象解构来获取 rawOptions 并将其分配给 raw 变量,默认值为 true

        【讨论】:

          【解决方案4】:

          如果您想在 options 存在但 rawOutput 不存在时指定 false,请尝试此操作。

          const raw = options ? (options.rawOutput ? rawOutput : false) : true;

          【讨论】:

            【解决方案5】:

            您可以只使用逻辑运算符来做到这一点,

            const raw = options && options.rawOutput || true;
            

            这会将 raw 设置为 true,以防 options 或 options.rawOutput 为假。

            【讨论】:

              【解决方案6】:

              当我们讨论options 时,现在的方法是总是 定义对象,至少是默认值。因此,例如,在您的情况下,您将拥有:

              // list of all defaults value for options
              const defaultOptions = {
                rawOutput: true
              }
              
              
              // assuming you are in a function when you get the options
              function doSomething(userOptions) {
                // here you will have all the options, with `userOptions`
                // overrides the default options if they're defined.
                const options = {...defaultOptions, ...userOptions};
              
                if (options.rawOutput) {
                  // do stuff
                }
              }
              

              这很有帮助,尤其是当您有多个选项要通过时,并且您可以为大多数选项设置默认值。这样,您不必每次都检查是否存在任何对象或属性,并且您还可以清楚地列出选项的默认值,您可以更改(或从 JSON 中获取)而不会影响您的代码。

              【讨论】:

                猜你喜欢
                • 2013-09-10
                • 2020-05-21
                • 1970-01-01
                • 2012-07-22
                • 2017-12-05
                • 1970-01-01
                • 2013-03-06
                • 2019-11-09
                • 2015-03-28
                相关资源
                最近更新 更多