【问题标题】:Combine indexOf and regexp match in Javascript array在 Javascript 数组中结合 indexOf 和 regexp 匹配
【发布时间】:2020-10-03 10:17:16
【问题描述】:

我需要返回数组中包含false 的字符串的位置。

[​"2: true", "4: true", ​"7: false", ​"8: true", ​"10: true"]

以下代码返回位置重置的新数组,应为2

return arrCom.filter(s => s.includes("false"));

【问题讨论】:

  • 为什么是.indexOf()?为什么是正则表达式?为什么.filter()?为什么.includes()
  • 我正在尝试学习他们的机制,因此在开发解决方案时会考虑到他们。
  • filter 帮助我创建了拆分数组以将truefalse 分开。这些记录由include 跟踪。 RegExp 是我考虑到的一种可能性。

标签: javascript arrays sorting filter


【解决方案1】:

不需要正则表达式或indexOf。要查找与任意条件匹配的数组中第一个条目的索引,请使用findIndex

const index = array.findIndex(entry => entry.includes("false"));

现场示例:

const array = ["2: true", "4: true", "7: false", "8: true", "10: true"];
const index = array.findIndex(entry => entry.includes("false"));
console.log(index);

如果您想要条目本身,您可以使用find

如果可能有多个匹配项并且您想要所有它们的索引,最简单的方法是使用循环:

const indexes = [];
for (let i = 0; i < array.length; ++i) {
    if (array[i].includes("false")) {
        indexes.push(i);
    }
}

现场示例:

const array = ["2: true", "4: true", "7: false", "8: true", "10: true"];
const indexes = [];
for (let i = 0; i < array.length; ++i) {
    if (array[i].includes("false")) {
        indexes.push(i);
    }
}
console.log(index);

【讨论】:

  • 我以前用过indIndex:,但没有运气。也许是因为我没有在浏览器中重置我的缓存。非常感谢!
【解决方案2】:

您可以使用Array.reduce 获取包含false 的索引数组。 在下面的例子中,Array.reduce中回调的第三个参数代表当前索引。

您可以在this link了解更多关于Array.reduce的信息

const input = [ "2: true", "4: true", "7: false", "8: true", "10: true" ];
const output = input.reduce((acc, curV, curI) => {
  if (curV.includes('false')) {
    acc.push(curI);
  }
  return acc;
}, []);

console.log(output);

【讨论】:

  • reduce 对此没有意义。 OP 正在寻找匹配条目的索引。这正是findIndex 的用途。
  • 这里需要的结果是索引值所以不用Array.filter。最好使用Array.forEachArray.reduceArray.reduce 更好,所以我已经提到了。
  • 这是回复我的意思吗?我什么都没说filterreduce 并不比我提到的要好,findIndex。 (另外,除非您使用预定义的可重用 reducer 进行函数式编程,否则reduce 几乎总是不必要的复杂。)
  • 我没有使用Array.findIndex,因为可以有多个变量包含false。而Array.reduce 可以很好地获取所有索引。当然,如果只需要一个索引,Array.findIndex 更好。
猜你喜欢
  • 2011-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多