问题描述
问题
编写一个获取序列和值并根据变量是否存在于多维序列中而返回true/false的函数.
Write a function that gets a sequence and value and returns true/false depending on whether the variable exists in a multidimensional sequence.
示例:
locate(['a','b',['c','d',['e']]],'e'); // should return true
locate(['a','b',['c','d',['e']]],'a'); // should return true
locate(['a','b',['c','d',['e']]],'f'); // should return false
我的解决方案似乎可以工作,但是Code Wars说:"arr.flat不是函数.
我使用免费的代码集中浏览器来运行和测试我的代码,我的控制台日志提示我可以运行它,但是Code Wars表示arr.flat不是一个功能.这是我的代码:
I use the free code camp browser to run and test my code, and my console logs suggested I had it working, but Code Wars was saying arr.flat is not a function. Here is my code:
var locate = function(arr, value){
let count = 0;
arr.flat().map((item)=>{
value == item ? count++ : count;
});
return count > 0 ? true : false;
}
我的问题
我的代码正确吗?如果没有,那是什么问题.如果是这样,为什么《代码大战》会引发错误?
Is my code correct or not? If not, what's wrong. If so, why might Code Wars be throwing an error?
推荐答案
您实际上并不需要.flat
(尽管这将允许const locate = (arr, value) => arr.flat().includes(value);
的最优雅的解决方案).这是一个使用普通for
循环的简单递归解决方案:
You don't actually need .flat
for this (although that would allow the most elegant solution of const locate = (arr, value) => arr.flat().includes(value);
). Here's a simple recursive solution using an ordinary for
loop:
const locate = function(arr, value) {
for(let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i]) {
if (locate(arr[i], value) {
return true;
}
}
if (arr[i] === value) {
return true;
}
}
return false;
}
这篇关于搜索多维数组(算法)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!