-1

我有javascript数组。我需要从这个数组中匹配并选择单词。

var tomatch = "";

var sets= new Array()
     sets[0]='nnd';
     sets[1]='nndha';
     sets[2]='ch';
     sets[3]='gn';

举个例子……什么时候,

  var tomatch = "nn";

它需要tomatch并 写出结果sets[0] & sets[1]

什么时候tomatch = "c",它应该与sets[2] 我该怎么做?

那里我不需要订单。
如果tomatch = "dh",也可以是sets[1]

我对javascript不太了解。

这个怎么做?

4

7 回答 7

2

Use the following function to return an array of matched words otherwise alert no match:

function find_match(to_match)
{
    match_array=new Array();
    for(i in sets)
    {
        if(sets[i].indexOf(to_match)!=-1)
            match_array.push(sets[i]);
    }
    return (match_array.length==0? alert('No match'): match_array);
}

To find match for say string 'n' you need to call find_match('n') which will return nnd,nndha,gn

于 2013-10-24T05:08:53.987 回答
2

indexof("string to match") 将返回字符串的索引,如果未找到该字符串,则返回 -1。只需遍历数组并检查 indexof("string to match") 的返回值是否为 -1。

sets[i].indexOf("nn")!=-1
于 2013-10-24T04:30:00.740 回答
0

谢谢大家,但这是我想要的,我认为 match cmd 适合我的任务。

  var sugest = "";
  var matchkeyword = "nn";

  var sets= new Array()
    sets[0]='nnd';
    sets[1]='nndha';
    sets[2]='ch';
    sets[3]='gn';
    sets[4]='nch';
    sets[5]='fu';
    sets[6]='Nui';


for(var i=0; i < sets.length ; i++){    

        if(sets[i].match(matchkeyword) != null) {
                    sugest = sugest + "<br>" + sets[i];
        }
}

 y=document.getElementById("sugdiv");
 y.innerHTML = sugest;
于 2013-10-24T05:55:13.190 回答
0
var tomatch = "nn";
var sets= new Array()
     sets[0]='nnd';
     sets[1]='nndha';
     sets[2]='ch';
     sets[3]='gn';    
for(var i=0; i < sets.length ; i++){
       if(sets[i].indexof(tomatch) !== -1){
         return sets[i];
       }
    }
于 2013-10-24T04:33:30.297 回答
0

This is not as neat as @Nirk's solution (I always forget about Array.filter) but you can replace my test function with Array.filter per his answer:

function test(a, f) {
  var i = 0,
      result = [];

  for (i=0; i<a.length; i++) {
    result.push(f(a[i]));
  }

  return result;
}

function txtMatch(s) {
  var pattern = new RegExp('' + s + '');
  return function(t) {
    return pattern.test(t);
  };
}

var sets= new Array()
sets[0]='nnd';
sets[1]='nndha';
sets[2]='ch';
sets[3]='gn';

var toMatchFirst = test(sets, txtMatch('nn'));
var toMatchSecond = test(sets, txtMatch('c'));

console.log(toMatchFirst.join(', '));
console.log(toMatchSecond.join(', '));

I just created a quick string match function and then loop through the array, testing each, and returning an array of the results.

于 2013-10-24T05:08:15.040 回答
0

它应该是:

   function isInArray(string){
     return sets.indexOf(string)>-1;      
   }

   alert(isInArray("nn"));

或者使用 jQuery:

jQuery.inArray("nnd",sets);

它将返回“nnd”的索引

于 2013-10-24T05:04:12.900 回答
0

使用过滤器:

> sets.filter(function(x) { return x.indexOf("nn") !== -1; })
[ 'nnd', 'nndha' ]
> sets.filter(function(x) { return x.indexOf("c") !== -1; })
[ 'ch' ]
于 2013-10-24T04:48:04.037 回答