【问题标题】:can i push the index in recursive function? [duplicate]我可以在递归函数中推送索引吗? [复制]
【发布时间】:2021-12-17 03:53:37
【问题描述】:

我的递归数组,我应该找到最后一个元素和索引

let array = [1, [2, "kkkk", [9, "some", ["six", "seven", 6666, [8, "10", [10,["you find me"]]]]]]];

function findIndex(arr) {
    for (let [index, element] of arr.entries()){
        let array = [];
        if(typeof element === "object"){
            findIndex(element);
            array.push(index);
            console.log(array);
        }
    }
}    
findIndex(array)
  1. 我添加了这一行 let array = []

  2. 在控制台中我应该只有这样的索引 [1,2,2,3,2],但现在我在不同的数组中都有索引 [1][2].....

  3. 它必须是递归函数。

  4. 我可以用这个例子吗?

【问题讨论】:

    标签: javascript function recursion indexing push


    【解决方案1】:
    let array = [1, [2, "kkkk", [9, "some", ["six", "seven", 6666, [8, "10", [10, ["you find me"]]]]]]];
    
    const getIndexArray = (array) => {
    
      const recursiveFnc = (array, acc = []) => {
    
        // Get index of the last element in a current array
        const lastIndex = array.length - 1;
        // Get the last element in a current array
        const lastElement = array[lastIndex];
    
        // Push index of last element
        acc.push(lastIndex);
    
        // If last element is an array go in that array recursively, if not return the last element
        return Array.isArray(lastElement) ? recursiveFnc(lastElement, acc) : acc;
      };
    
      return recursiveFnc(array);
    
    };
    
    const result = getIndexArray(array);
    

    【讨论】:

      猜你喜欢
      • 2013-01-10
      • 2013-05-05
      • 2019-06-10
      • 2015-12-30
      • 2010-09-16
      • 2011-03-05
      • 1970-01-01
      • 2011-08-17
      相关资源
      最近更新 更多