英文:
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));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论