【问题标题】:JavaScript assign value to variable only if certain condition is met (without repetition)JavaScript 仅在满足特定条件时才为变量赋值(不重复)
【发布时间】:2019-03-13 04:24:35
【问题描述】:

假设我正在定义一个这样的 JavaScript 变量:

var sheetsToWorkWith =
    (
        allSheets.length > 0 ?
        allSheets
        .filter(x =>
            x.cssRules && [].slice.call(x.cssRules).filter(y =>
                Object.keys(data).includes(y.selectorText)
            ).length > 0
        ) :
        []
    ) ||
    (() => {
        var style = head.appendChild(document.createElement("style"));
        style.type = "text/css";
        return style.sheet;
    })(),

这个变量赋值 (did/) 所做的基本上是检查现有样式表是否存在,如果不存在,则将其分配给新样式表。我现在想要它做的是将它设置为样式表列表,其中任何一个都包含一个与预定义数组中的元素匹配的 selectorText,但是似乎这样做我需要两个变量:我想设置仅当结果的长度大于 0 时,它才等于第一个值(|| 运算符的右侧/顶部)。

【问题讨论】:

  • || 之后的表达式永远不会被计算,因为第一个表达式总是返回一个数组。空数组不是虚假的。

标签: javascript


【解决方案1】:

如果您仅在 allSheets.length > 0 为真时才需要数组中的第一个值,则只需通过索引 [0] 引用第一个元素。

var sheetsToWorkWith = (
  allSheets.length > 0 ?
    allSheets.filter(x => 
      x.cssRules && [].slice.call(x.cssRules).filter(y => 
        Object.keys(data).includes(y.selectorText)))[0] // index the first element
  :
    []
  )
||
...

请注意,Array.prototype.filter 始终返回一个数组,按索引访问空数组会导致 undefined 确保您的第一个表达式返回三元组 ([]) 的 else 部分。

编辑

OP 希望评估三元组的 else 部分,因此,可以做的是:

var sheetsToWorkWith = (
  allSheets.length > 0 ?
    allSheets.filter(x => 
      x.cssRules && [].slice.call(x.cssRules).filter(y => 
        Object.keys(data).includes(y.selectorText)))[0] // index the first element
  :
    (() => {
        var style = head.appendChild(document.createElement("style"));
        style.type = "text/css";
        return style.sheet;
    })()
  )

【讨论】:

  • 我想要整个数组,但前提是它的长度大于0,如果是0,则继续||
  • 就像我在 cmets 中所说的,|| 之后的表达式永远不会被计算。我会更新我的答案来解决这个问题。
  • || 之后的表达式不会返回实际工作表,即使有 return style.sheet,因为它的范围不同,read about IIFE。您需要将其分配给某些东西。 var myResult = (() => { ... return style.sheet; })() 和现在 myResult 将拥有您的工作表。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-21
  • 1970-01-01
  • 2022-11-24
  • 1970-01-01
相关资源
最近更新 更多