我有一个多维数组,我想在该数组中找到用户输入的字符串。我想存储它的索引(它们两个,就像字符串在arr[a][b]
,我需要a
和b
的值。
例如,我有一个如下的数组,想要找到单词"scar",我怎么才能得到它?
var arr=[["hey","oh"],["scar","tissue"],["other","side"]];
我已经尝试了以下代码块:
var a;
var b;
for (var z = 0; z < arr.length; z++) {
for (var i = 0; i < 2; i++) {
if (arr[z][i] === "scar") {
b = z;
a = i;
}
}
}
我试着搜索和研究这个问题,但找不到一个。
你可以用多种方式搜索你的字符串
使用嵌套的for-for
for (a = 0; a < arr.length; a++){
for (b=0; b < arr[a].length; b++){
if (arr[a][b] == mySearch){
return true;
}
}
}
使用嵌套的forEach
var found = false;
arr.forEach(function(a) {
a.forEach(function(b) {
if (b == wordToFind) {
found = true;
}
});
});
return found;
您可以循环每个子数组,然后使用indexOf()
函数检查是否找到所需的索引:
var arr = [["hey","oh"], ["scar","tissue"], ["other","side"]];
function get_index_of_string(my_array, mystring) {
var a = 0;
var results = [];
var b, subarray;
for (var arrayIndex in my_array) {
subarray = my_array[arrayIndex];
var search = subarray.indexOf(mystring)
if (search != -1){
a++;
b = search;
}
}
results[0] = a;
results[1] = b;
return results;
}
var results = get_index_of_string(arr,"scar");
if (results[0] != -1 && results[1] != -1) {
alert("String is found in the " + results[0] + " subarray in the " + results[1] + " index");
} else{
alert("String is not found");
}