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

使用Array.findIndex时触发TypeError: string is not a function错误求助

问题分析与解决

错误原因

你遇到的TypeError: string "z" is not a function是因为**Array.findIndex()必须传入一个回调函数**,而你直接传了字符串'z'。JS会尝试把这个字符串当作函数执行,所以抛出错误。

修正代码与功能实现

下面是修正后的代码,同时实现你需要的「获取z的索引,提取z及之前所有元素并转大写」的功能:

const chars: string = "abcdefghilmnopqrstuwxyz0123456789@-_+*(),.#";
let outputMatrix: Array<string> = [];

// Split input matrix function 
const splitMatrix = (inputMatrix: string) => {
  const splitted = inputMatrix.split(''); 
  // 用回调函数判断元素是否为'z',获取其索引
  const zIndex = splitted.findIndex(char => char === 'z');
  
  if (zIndex !== -1) {
    // 截取z及之前的元素,转大写
    const upperCasePart = splitted.slice(0, zIndex + 1).map(char => char.toUpperCase());
    console.log('Z及之前的大写元素:', upperCasePart);
    console.log('对应的字符串:', upperCasePart.join(''));
  } else {
    console.log('未找到字符z');
  }
  
  console.log('拆分后的完整数组:', splitted);
  return splitted;
}

// Generating random word
const createRandomString = (splittedChars: Array<string>, length?: number) => {
  const defaultLength: number = 12;
  const min: number  = 0;
  const max: number = splittedChars.length;
  // 把outputWord改成局部变量,避免多次调用累加
  let outputWord: string = "";
  let num: number;

  const targetLength = length || defaultLength;
  for(let i: number = 0; i < targetLength; i++) {
    num = Math.floor(Math.random() * (max - min) + min);
    outputWord += splittedChars[num];
  }
  
  console.log('Generated password', outputWord);
  return outputWord;
}

const main = () => {
  const splitted = splitMatrix(chars);
  createRandomString(splitted);
}

main();

关键修正点

  • 把splitted.findIndex('z')改为splitted.findIndex(char => char === 'z'),正确使用findIndex的回调函数语法
  • 添加了截取z及之前元素并转大写的逻辑
  • 将outputWord从全局变量改为createRandomString内的局部变量,避免多次调用时字符串累加
  • 移除了splitMatrix不必要的async修饰符(函数内没有异步操作)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 06:05:03