我正在尝试编写一个递归函数来定位多维数组中的值。这是我到目前为止所尝试过的:
var locate = function (arr,value) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === value) {
return true;
} else if (Array.isArray(arr[i])) {
locate(arr[i], value);
}
}
return false;
}
但是,它不起作用:
console.log(locate(['a','b',['c','d',['e']]],'e'))
// => returns `false`, but should return `true`
我应该如何解决这个问题?
最佳答案
这是一个递归 DFS:
var locate = function (arr, value) {
// start at the current array; we want to check every value
for (var i = 0; i < arr.length; i++) {
// if we've found our value, return immediately
if (arr[i] === value) {
return true;
// if the element is an array, call locate on the element
// and possibly return true
// we don't want to return locate(arr[i], value) because
// it could be found later on
} else if (Array.isArray(arr[i]) && locate(arr[i], value)) {
return true;
}
}
// reached the end of the current array, so return `false`
// note, since we use `else if (... locate(arr[i], value)),
// we won't stop the recursion before checking every possible value
return false;
}
关于javascript - 如何编写递归来定位多维数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29691435/