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

如何高效判断给定字符串是否为数组中任意元素的前缀

报错原因说明

你遇到的contains is not a function报错,是因为JavaScript原生数组没有内置contains方法,该方法为非标准实现,无法在所有环境下正常运行。

基础实现方案(适配绝大多数场景)

要实现「判断数组中是否存在以指定字符串为开头的元素」的需求,可以组合使用数组Array.prototype.some()方法和字符串String.prototype.startsWith()方法:

  • some()方法会遍历数组,只要有一个元素满足判断条件就会立即终止遍历返回true,无需遍历完整数组,性能表现优异
  • startsWith()方法会判断当前字符串是否以传入的参数字符串为开头,返回布尔值

代码示例

// 示例数组
const array_to_search = ["systematic plan","superscript", "subset"];

// 封装判断方法
function hasStartWithItem(arr, targetPrefix) {
  return arr.some(item => item.startsWith(targetPrefix));
}

验证测试结果

和你给出的示例要求完全匹配:

  • hasStartWithItem(array_to_search, "systematic") → true
  • hasStartWithItem(array_to_search, "super") → true
  • hasStartWithItem(array_to_search, "matic") → false
  • hasStartWithItem(array_to_search, "plan") → false
  • hasStartWithItem(array_to_search, "mmatic") → false
  • hasStartWithItem(array_to_search, "superset") → false
  • hasStartWithItem(array_to_search, "superscript") → true
  • hasStartWithItem(array_to_search, "script") → false

旧环境兼容方案

如果运行环境不支持ES6新增的startsWith方法,可以用indexOf代替判断:

function hasStartWithItem(arr, targetPrefix) {
  return arr.some(item => item.indexOf(targetPrefix) === 0);
}

超大数据量优化方案

如果数组元素量级过万且需要多次执行查询操作,可以提前为数组构建字典树(Trie)结构,一次构建后后续所有查询的时间复杂度仅为O(k),k为查询字符串的长度,性能远高于逐一遍历方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 09:15:03