如何通过函数链在Javascript中简化这段代码?

huangapple go评论63阅读模式
英文:

How to simplify this code in Javascript via function chaining?

问题

我想知道如何通过链接它们来简化这些函数调用。有没有一种方法可以链接 forEach、push、解构数组和 map。

let selectorsForLoader = ['a', 'b'];
let loadingElements = [];
selectorsForLoader.forEach(selector => {
  loadingElements.push(...Array.from(document.querySelectorAll(selector)));
});
let loaders = loadingElements.map(loadingElement => {
  loadingElement.doSomething();
});

这是我所说的函数链接的示例:

food.map(item => item.type)
  .reduce((result, fruit) => {
    result.push(fruit);
    return [...new Set(result)];
  }, []);
英文:

I would to know how to simplify theses function calls by chaining them. Is there a way to chain forEach, push, destructuring array and map.

 let selectorsForLoader = ['a', 'b'];
 let loadingElements = [];
    selectorsForLoader.forEach(selector => {
      loadingElements.push(...Array.from(document.querySelectorAll(selector)));
    });
    let loaders = loadingElements.map(loadingElement => {
      loadingElement.doSomething();
    });

Here is an example of what I mean by function chaining:

   food.map(item => item.type)
  .reduce((result, fruit) => {
    result.push(fruit);
    return [...new Set(result)];
  }, []);

答案1

得分: -1

这是您的代码的中文翻译:

这是您的代码的中文翻译

['a', 'b'].flatMap(selector => {
    return Array.from(document.querySelectorAll(selector)));
}).forEach(loadingElement => {
    loadingElement.doSomething();
});

顺便说一下你提供的示例应该这样写

new Set(food.map(item => item.type));
英文:

There you go:

['a', 'b'].flatMap(selector => {
    return Array.from(document.querySelectorAll(selector)));
  }).forEach(loadingElement => {
    loadingElement.doSomething();
  });

By the way, that "example" you gave should be written like this:

new Set(food.map(item => item.type));

huangapple
  • 本文由 发表于 2023年7月18日 16:15:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76710765.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定