首页 > 其他 > 详细

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

时间:2018-06-26 15:40:36      阅读:214      评论:0      收藏:0      [点我收藏+]

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

写一个类似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]

 

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

原文:https://www.cnblogs.com/viola-sh/p/9229223.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!