我如何使用 spreader 和 gather 运算符在 Es6 中实现跟随?

How can i achieve following in Es6 using spreader and gather operator?

我正在检查选择器是否具有某个 class、id 或两者。如果 id、class 或两者都匹配,eitherClassIdOrBoth() 会将选择器推入 elements 数组。它工作得很好,但我想知道我是否可以使用 spread operator 在 ES6 中实现这一点。

这是 returns 布尔值的地方:

var idAndClassMatch = function(matchId, matchClass, matchBoth) {
return (
(matchBoth && matchId && matchClass) || (!matchBoth && (matchId || matchClass))); }

这是我要使用展开运算符的函数:

var elements = []

function eitherClassIdOrBoth(
   selectId, selectClass, array, matchBoth, elements
) 
{

   for (let i = 0; i < array.length; i++) {
      var classSection = array[i].className.split(" ");
      var matchId = selectId !== undefined && array[i].id === selectId;
      var matchClass = classSection !== undefined && 
          classSection.indexOf(selectClass) !== -1;

      if (idAndClassMatch(matchId, matchClass, matchBoth)) {
          elements.push(array[i]); 
      }
   }
}

我从 if 语句传递这些值:

if (arr.length === 2) {
    computedFunction.eitherClassIdOrBoth(
        selectId, selectClass, tags, false, Allelements
    );
}

任何帮助都将非常有帮助!

有更好的方法来编写这个逻辑,但要点可能不是 ES6 特定的。

最让我吃惊的是,整个函数的主要查询可以替换为对 Element#matches 的调用,后者根据 CSS 选择器检查元素。它在旧版浏览器上并不始终可用,但加载 polyfill 以确保它可用是微不足道的。那么你的整个

computedFunction.eitherClassIdOrBoth(
    selectId, selectClass, tags, false, Allelements
);

电话会是

Allelements.push(
  ...tags.filter(tag => tag.matches(`.${selectClass}, [id="${selectId}"]`)
);

例如使用 .filter.matches 创建一个仅包含给定 tags 数组的项目的新数组,然后使用 ES6 传播轻松将所有项目推入 Allelements 数组.

您似乎有一些情况 selectClassselectId 可能是 undefined,因此您也可以构建该查询,例如

const selector = [
  selectClass ? `.${selectClass}` : "",
  selectId ? `[id="${selectId}"]` : "",
].filter(Boolean).join(",");
Allelements.push(
  ...tags.filter(tag => selector ? tag.matches(selector) : false
);

并且对于 matchBothtrue 的情况,您只需使用 "" 而不是 "," 加入选择器。所以你最终会得到

function eitherClassIdOrBoth(
   selectId, selectClass, array, matchBoth, elements
) {
    const selector = [
      selectClass ? `.${selectClass}` : "",
      selectId ? `[id="${selectId}"]` : "",
    ].filter(Boolean).join(matchBoth ? "" : ",");
    if (selector) {
      elements.push(...array.filter(tag => tag.matches(selector));
    }
}

如果你想要一个通用的工具。