[英]JavaScript assign value to variable only if certain condition is met (without repetition)
说我正在定义这样的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 /)的作用是检查是否存在现有样式表,如果不存在,则将其分配给新样式表。 我现在想要做的是将其设置为样式表列表,其中的任何一个都包含与预定义数组中的元素匹配的选择器文本,但是这样做似乎需要两个变量:我要设置仅当结果的长度大于0时,它才等于第一个值(在||运算符的右侧/顶部)。
如果仅当allSheets.length > 0
为true时才需要数组中的第一个值,则只需按索引[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;
})()
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.