2015-11-07 45 views
-1

实际的问题是,这个(堆栈溢出的问题,限制字符):如何检查字符串是否存在于多维数组中,然后显示数组中的第一个字符串被找到的项目?

如何检查一个字符串是否从一个(非静态)多维数组的文本框出现,然后显示在第一项从哪个数组中找到该字符串? (使用jQuery)

例如:。

(这不是我实际上做的,这只是一个例子,我明白我提供有一个更简单的解决方案的例子这不是我后,虽然)

HTML

<input type="text" id="textbox"> 
<div id="output"></div> 

JS:

var array = [ 
    ["that's an ice-cream topping","sprinkles","chocolate syrup"], 
    ["that's a pizza topping","basil","cheese"], 
    ["that's a car part","wheel","headlights","windshield wipers"] 
]; 

('#textbox').keyup(function(){ 
    if(/*a match is found from the textbox in the array*/){ 
     ('#output').html(/*first item in the array the string was found in*/); 
    } else { 
     ('#output').html(); 
    } 
}); 

这就是我想要实现: 如果用户键入“洒东西”,在文本框中,只要“洒”被输入,输出会显示“这是一个冰淇淋配料。”

附注:这里假设在文本框中输入“这是冰淇淋打顶”,也会显示“这是冰淇淋打顶”。这也假定数组可以被改变并且从不相同。

+0

['Array.prototype.find'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) – Andreas

+0

这可以帮助你:http://stackoverflow.com/questions/8809425/search-multi-dimensional-array-javascript –

回答

0

你可以做这样的事情:

$('#textbox').keyup(function() { 
    var searchResult = findMatch($(this).val()); 
    if (searchResult) { 
     $('#output').html(searchResult); 
    } else { 
     $('#output').html(''); 
    } 
}); 

function findMatch(enteredString) { 
    for (var i in array) { 
     if ($.inArray(enteredString, array[i]) !== -1) { 
      return array[i][0]; 
     } 
    } 
    return ''; 
} 
+0

非常感谢你!这工作很好!但是,我应该澄清,我不需要找到完全匹配。 $ .inArray查找值的完全匹配。我只需要看看这个值是否存在于importedString的开头。任何帮助? – Lolsdasfgnhg

+0

@Lolsdasfgnhg使用'array [i] .indexOf(enteredString)=== 0'来匹配被输入的字符串的开头 – Sean

+0

@Sean你是否在if语句中表示?如果是这样,我不敢说这是行不通的。 – Lolsdasfgnhg

相关问题