在javascript中搜索并查找多维数组中字符串的索引

时间:2015-07-27 06:54:16

标签: javascript arrays multidimensional-array

我有一个多维数组,我想在该数组中找到用户输入的字符串。我想存储它的索引(两者都是,就像字符串是arr[a][b]一样,我需要ab的值。

例如,我有一个如下数组,想要找到" 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;
    }
  }
}

我尝试搜索和研究这个问题但却找不到问题。

提前致谢。

2 个答案:

答案 0 :(得分:0)

您可以通过多种方式搜索字符串

使用嵌套的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;

答案 1 :(得分:0)

你可以遍历每个子数组,然后使用函数indexOf()检查是否找到了所需的索引:

&#13;
&#13;
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");
}
&#13;
&#13;
&#13;