如何检查多维数组中是否存在字符串,然后显示数组中找到该字符串的第一个项

How do i check if a string is present in a multidimensional array and then display the first item in the array that the string was found in?

本文关键字:数组 字符串 然后 显示 第一个 是否 何检查 检查 存在      更新时间:2023-09-26

实际问题是(堆栈溢出限制问题中的字符):

如何检查(非静态)多维数组中的文本框中是否存在字符串,然后显示在其中找到该字符串的数组中的第一个项?(使用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();
    }
});

这就是我正在努力实现的目标:如果用户在文本框中键入"sprinkles and stuff",那么一旦键入"sprickles",输出就会显示"那是冰淇淋浇头。"

旁注:这假设在文本框中键入"that’s an冰激凌浇头"也会显示"that‘s an冰激凌topin"。这也假设数组可以更改,并且永远不会相同。

您可以这样做:

$('#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 '';
}