【问题标题】:How to check if a string contains text from an array of substrings in NodeJS and then find the index of that substring in the array?如何检查字符串是否包含 NodeJS 中子字符串数组中的文本,然后在数组中找到该子字符串的索引?
【发布时间】:2023-03-31 01:54:02
【问题描述】:

我能够确定问题的第一部分,即如果字符串包含来自 NodeJS 中的子字符串数组的文本,则返回 true:

var allowedRoles = [
    "Area Director",
    "Managing Director",
    "Group Director"];

var currentRole = "USA Managing Director";
var lifeSaver = allowedRoles.some((substring) =>
    currentRole.includes(substring)
);
console.log(lifeSaver);

这里我的结果是正确的。 但是,我想知道在 allowedRole 数组中我的结果返回 true 的位置。 (预期答案:1);

【问题讨论】:

  • 您可以将.some()替换为.findIndex()

标签: javascript arrays node.js express ecmascript-6


【解决方案1】:

你可以使用.findIndex而不是.some

findIndex() 方法返回第一个元素的索引 满足提供的测试功能的数组。否则,它 返回-1,表示没有元素通过测试。

var lifeSaver = allowedRoles.findIndex((substring) =>    
    currentRole.includes(substring)
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-31
    • 2021-12-14
    • 2020-11-28
    • 1970-01-01
    相关资源
    最近更新 更多