繁体   English   中英

如何使用javascript函数在数组数组中搜索字符串

[英]How to search for a string in array of arrays using javascript function

此函数能够在数组中搜索字符串:

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']]

您可以尝试“查找”方法

let arr = [['one','two'],['three','four'],['five','six']];

function searchInMultiDim(str) {
    return arr.find(t => { return t.find(i => i === str)}) && true;
}

searchInMultiDim('one');

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

 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

试试这个代码:

 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"]]))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM