我们必须编写一个函数,说它searchRecursively()
接受一个数组和一个搜索查询,然后在嵌套数组中返回该搜索查询的计数。
例如,如果数组由-给定
const names = ["rakesh", ["kalicharan", "krishna", "rakesh", "james", ["michael", "nathan", "rakesh", "george"]]];
然后-
searchRecursively(names, ‘’rakesh’);
应该返回3,因为它在数组中总共出现3次。因此,让我们为该递归函数编写代码-
const names = ["rakesh", ["kalicharan", "krishna", "rakesh", "james", ["michael", "nathan", "rakesh", "george"]]]; const searchRecursively = (arr, query, count = 0, len = 0) => { if(len < arr.length){ if(Array.isArray(arr[len])){ return searchRecursively(arr[len], query, count, 0); }; if(arr[len] === query){ return searchRecursively(arr, query, ++count, ++len); }; return searchRecursively(arr, query, count, ++len); }; return count; }; console.log(searchRecursively(names, "rakesh"));
输出结果
控制台中的输出将为-
3