2011-11-13 22 views
0

当数组中的字符与搜索词相匹配而不管数组中的字符顺序时,我试图从数组中返回索引。挣扎当字符匹配模式时从数组返回索引

array = ['hell on here', '12345', '77788', 'how are you llo'] 

function charmatch(array,lookFor){ 
Indexarray = []; 

for(I=0; I<array.length;I++){ 
If (lookFor.charAt(I) <= array.indexOf(I)) 
Indexarray[Indexarray.length] = I 

} return Indexarray;因此这应该在数组中返回0,3。这怎么能做到?

回答

0

这应做到:

function charmatch(arr, lookfor) { 
    var result = [], 
     split, 
     found = false; 

    // Iterate over every item in the array 
    for (var i = 0; i<arr.length; i++) { 
     found = false; 
     // Create a new array of chars 
     split = arr[i].split(''); 
     // Iterate over every character in 'lookfor' 
     for (var j = 0; j<lookfor.length; j++) { 
      found = false; 
      // Iterate over every item in the split array of chars 
      for (var k=0; k<split.length; k++) { 
       // If the chars match, then we've found one, 
       // therefore exit the loop 
       if (lookfor.charAt(j) === split[k]) { 
       found = true; 
       break; 
       } 
      } 
      // char not found, therefor exit the loop 
      if (!found) { 
       break; 
      } 
      // Remove the first item (which is a char), thus 
      // avoiding matching an already matched char 
      split.shift(); 
     } 
     // if 'found' is true by now, then it means all chars have been found 
     if (found) { 
      // Add the current index to the result array 
      result.push(i); 
     } 
    } 
    return result; 
} 

charmatch(['hell on here', '12345', '77788', 'how are you llo'], 'hello');