只有在满足某些条件时,JavaScript才会将值赋给变量(不重复)

问题描述 投票:0回答:1

说我正在定义一个像这样的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;
    })(),

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

javascript
1个回答
0
投票

如果只想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;
    })()
  )
© www.soinside.com 2019 - 2024. All rights reserved.