搜索2D阵列最干净的方法?

JCO*_*611 5 javascript arrays

我能想到的最简单的方法是for循环:

var arr=[["hey","oh"],["scar","tissue"],["other","side"]];
var query="scar";
for(var z=0;z<arr.length;z++){
   if(arr[z].indexOf(query) !== -1){
      //Found
      break;
   }
}
Run Code Online (Sandbox Code Playgroud)

有没有其他方法可以在2D数组中搜索字符串?

Nei*_*eil 11

var arr = [["hey","oh"],["scar","tissue"],["other","side"]];
var flat = [].concat.apply([], arr);
var col = flat.indexOf(query);
var row = -1;
if (col != -1) // found, now need to extract the row
  while (arr[++row].length <= col) // not this row
    col -= arr[row].length; // so adjust and try again
Run Code Online (Sandbox Code Playgroud)

  • @tomdemuyt是的,如果已知数组为矩形,则该方法有效. (2认同)