【问题标题】:How to search for a string in array of arrays using javascript function如何使用javascript函数在数组数组中搜索字符串
【发布时间】:2019-02-01 01:57:27
【问题描述】:

此函数可以在数组中搜索字符串:

public checkElement( array ) {        
    for(var i = 0 ; i< array.length; i++) {
        if( array[i] == 'some_string' ) {
            return true;
        }      
    }
 }

如何在 for 循环中使用数组数组?我想将此传递给一个使用 if 条件搜索字符串的函数。

示例输入: array[['one','two'],['three','four'],['five','six']].

【问题讨论】:

  • 请在您的整体任务中搜索更多子任务,例如,如何在 java 脚本中比较字符串以及如何在 javascript 中迭代多维数组。希望这会有所帮助。
  • 顺便说一句,你从哪里得到public
  • 我使用 typescript 类。所以我将方法定义为公共的。

标签: javascript arrays search multidimensional-array


【解决方案1】:

试试这个代码:

function checkElement(array){        
 for(value of array){
  if(value.includes("some string")){return true}
 }
 return false
}
console.log(checkElement([["one","two"],["three","four"],["five","six"]]))
console.log(checkElement([["one","two"],["three","four"],["five","some string"]]))

【讨论】:

    【解决方案2】:

    这是一个递归解决方案,它检查一个项目是否是一个数组,如果它是搜索它的字符串。它可以处理多层嵌套数组。

    function checkElement(array, str) {
      var item;
      for (var i = 0; i < array.length; i++) {
        item = array[i];
        
        if (item === str || Array.isArray(item) && checkElement(item, str)) {
          return true;
        }
      }
      
      return false;
    }
    
    var arr = [['one','two'],['three','four'],['five','six']];
    
    console.log(checkElement(arr, 'four')); // true
    console.log(checkElement(arr, 'seven')); // false

    同样的想法使用Array.find():

    const checkElement = (array, str) =>
      !!array.find((item) =>
        Array.isArray(item) ? checkElement(item, str) : item === str
      );
    
    const arr = [['one','two'],['three','four'],['five','six']];
    
    console.log(checkElement(arr, 'four')); // true
    console.log(checkElement(arr, 'seven')); // false

    【讨论】:

      【解决方案3】:

      你可以试试“查找”方法

      let arr = [['one','two'],['three','four'],['five','six']];
      
      function searchInMultiDim(str) {
          return arr.find(t => { return t.find(i => i === str)}) && true;
      }
      
      searchInMultiDim('one');
      

      【讨论】:

      • 请注意,此解决方案仅适用于 2 级深度 - 也可能更好地处理更深的级别 - 或者至少在答案中提到这一点
      • @DavidWinder 根据问题,我认为不需要提及任何内容:) 但当然使其通用化会很有效
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-09
      • 1970-01-01
      • 2011-07-22
      相关资源
      最近更新 更多