zoukankan      html  css  js  c++  java
  • 一个类似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]
  • 相关阅读:
    HDU What Are You Talking About
    谷歌面试题
    POJ 2299 UltraQuickSort
    单链表排序
    HDU Hat’s Words
    C++ const关键字
    求二叉树任意两点间的距离
    HDU Phone List
    POJ 2352 Stars
    C++ volatile关键字
  • 原文地址:https://www.cnblogs.com/viola-sh/p/9229223.html
Copyright © 2011-2022 走看看