You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript根据部分字符串查找数组索引?

实现部分字符串匹配查找数组索引

你可以用数组的findIndex()方法,它支持传入回调函数,在回调里判断数组元素是否包含目标子串,以此找到对应索引:

var table = ['view-only-access', 'restricted-access', 'full-access'];

// 查找包含'view'的元素索引
const viewIndex = table.findIndex(item => item.includes('view'));
console.log(viewIndex); // 输出 0

// 查找包含'restricted'的元素索引
const restrictedIndex = table.findIndex(item => item.includes('restricted'));
console.log(restrictedIndex); // 输出 1

// 查找包含'full'的元素索引
const fullIndex = table.findIndex(item => item.includes('full'));
console.log(fullIndex); // 输出 2

如果要兼容不支持ES6语法的旧环境,可以用传统循环结合indexOf()判断子串:

function getIndexBySubstring(arr, substr) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].indexOf(substr) !== -1) {
      return i;
    }
  }
  return -1; // 未找到匹配项时返回-1
}

// 使用示例
const table = ['view-only-access', 'restricted-access', 'full-access'];
console.log(getIndexBySubstring(table, 'view')); // 0
console.log(getIndexBySubstring(table, 'restricted')); // 1

如果数组存在多个包含同一子串的元素,findIndex()只会返回第一个匹配项的索引;若要收集所有匹配的索引,可以用reduce():

const table = ['view-only-access', 'view-edit-access', 'restricted-access'];
const allViewIndices = table.reduce((indices, item, index) => {
  if (item.includes('view')) {
    indices.push(index);
  }
  return indices;
}, []);
console.log(allViewIndices); // 输出 [0, 1]

内容的提问来源于stack exchange,提问作者Faishal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 19:30:53