一个类似indexOf()的功能的函数

之前面试的时候遇到了这样的一道题,不过写的时候有些细节没注意到,现在重新写了一下。

写一个类似indexOf()的功能的函数

  var str = "dafdfgvdahjfbhyuyvturb";

  function indexOfFunc(str, txt) {
    let arr = str.split(""),
      index = -1;
    for (let i = 0; i < arr.length; i++) {
      if (txt == arr[i]) {
        index = i;
        break;
      } else {
        index = -1;
      }
    }
    return index;
  }
  var a = indexOfFunc(str, "j");
  console.log(a);  //10

  var b = str.indexOf("v");
  console.log(b);  //6

稍微改一下,可以写成返回所查字符在被查字符串中所有位置

  function existFunc(str, txt) {
    let arr = str.split(""),
      num = [],
      index = -1;
    for (let i = 0; i < arr.length; i++) {
      if (txt === arr[i]) {
        num.push(i);
      }
    }
    num = num.length > 0 ? num : -1;
    return num;
  }

  var c = existFunc(str, "b");
  console.log(c); //[12, 21]
原文地址:https://www.cnblogs.com/viola-sh/p/9229223.html