简体   繁体   English

使用递归达到嵌套数组项-javascript

[英]Reach nested array item using recursion - javascript

I'm trying to reach the center of a nested array using recursion. 我正在尝试使用递归到达嵌套数组的中心。 This is part of a larger problem I'm trying to solve. 这是我要解决的更大问题的一部分。 I'm sure the solution is somewhat elementary. 我敢肯定解决方案是基本的。 I've been learning JS/web dev and am stumped. 我一直在学习JS / Web开发人员,但是很困惑。

Here's my code: 这是我的代码:

var j = [[[["hey!"]]]];

function getNested(obj) {
for (var i = 0; i < obj.length; i++) {
    if (Array.isArray(obj[i])) {
        obj = obj[i];
        getNested(obj);
    } 
    return obj[i];
  } 
}

The function is supposed to return the 'hey!' 该功能应该返回“嘿!” string, but I can't seem to get it right. 字符串,但似乎无法正确处理。

You are close, just switch out the findType(obj) for return getNested(obj[i]) . 您接近了,只需将findType(obj) return getNested(obj[i]) This will give you a recursive function that drills down into the array until the item in the array is not another array. 这将为您提供一个递归函数,该函数可深入到数组中,直到数组中的项不是另一个数组为止。 Also, the for-loop was unnecessary, given your example input. 同样,鉴于您的示例输入,for循环也是不必要的。

This will only work if your nested arrays have exactly one element. 当嵌套数组只有一个元素时,此方法有效。 Others have expressed this in the comments. 其他人在评论中表达了这一点。

var j = [[[["hey!"]]]];

function getNested(obj) {
    if (Array.isArray(obj)) {
        return getNested(obj[0]);
    } 
    return obj;
}

var str = getNested(j);
console.log(str); // "hey!"

jsFiddle Demo jsFiddle演示

There is no need for recursion, a simple while loop will already do the trick 无需递归,简单的while循环就可以解决问题

var j = [[[["hey!"]]]];

function getNested(obj) {
    while (Array.isArray(obj)) { obj = obj[0]; } 
    return obj;
}

var str = getNested(j);
console.log(str); // "hey!"

The recursive implementation has the nice property that it is purely functional though if you rewrite it like so: 递归实现具有不错的属性,即它纯粹是功能性的,但是如果您这样重写它:

var j = [[[["hey!"]]]];

function getNested(obj) {
    return Array.isArray(obj)? getNested(obj[0]): obj;
}

var str = getNested(j);
console.log(str); // "hey!"

Still its performance would be worse though. 尽管如此,它的性能还是会更差。

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

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