所有匹配项的索引

JavaScriptJavaScriptBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在本实验中,我们将探索 JavaScript 中的 indexOfAll 函数。该函数使我们能够在数组中找到给定值的所有索引。通过使用 Array.prototype.reduce() 方法,我们可以轻松地遍历数组元素并存储匹配元素的索引。本实验将为你提供使用这个实用函数及其在 JavaScript 中的实现的实践经验。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("JavaScript")) -.-> javascript/BasicConceptsGroup(["Basic Concepts"]) javascript(("JavaScript")) -.-> javascript/AdvancedConceptsGroup(["Advanced Concepts"]) javascript/BasicConceptsGroup -.-> javascript/variables("Variables") javascript/BasicConceptsGroup -.-> javascript/data_types("Data Types") javascript/BasicConceptsGroup -.-> javascript/arith_ops("Arithmetic Operators") javascript/BasicConceptsGroup -.-> javascript/comp_ops("Comparison Operators") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("Higher-Order Functions") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("Spread and Rest Operators") subgraph Lab Skills javascript/variables -.-> lab-28388{{"所有匹配项的索引"}} javascript/data_types -.-> lab-28388{{"所有匹配项的索引"}} javascript/arith_ops -.-> lab-28388{{"所有匹配项的索引"}} javascript/comp_ops -.-> lab-28388{{"所有匹配项的索引"}} javascript/higher_funcs -.-> lab-28388{{"所有匹配项的索引"}} javascript/spread_rest -.-> lab-28388{{"所有匹配项的索引"}} end

所有匹配项的索引

要在数组中找到 val 的所有索引,请使用 Array.prototype.reduce() 遍历元素并存储匹配元素的索引。如果 val 从未出现过,则返回一个空数组。

const indexOfAll = (arr, val) =>
  arr.reduce((acc, el, i) => (el === val ? [...acc, i] : acc), []);

示例用法:

indexOfAll([1, 2, 3, 1, 2, 3], 1); // [0, 3]
indexOfAll([1, 2, 3], 4); // []

要开始练习编码,请打开终端/SSH 并输入 node

这是所有匹配项的索引。

总结

恭喜你!你已经完成了“所有匹配项的索引”实验。你可以在 LabEx 中练习更多实验来提升你的技能。