這個問題在這里已經有了答案: 為什么我不能在同一個陣列中推送索引?[關閉] (2 個回答) 12 小時前關閉。
我的遞回陣列,我應該找到最后一個元素和索引
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)
我添加這一行
let array = []在控制臺中,我應該只有這樣的索引 [1,2,2,3,2],但現在我在不同的陣列 [1][2].....
它必須是遞回函式。
我可以用這個例子來做嗎?
uj5u.com熱心網友回復:
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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/346136.html
標籤:javascript 功能 递归 索引 推
上一篇:如何使用用戶輸入的數學整數函式?
下一篇:在python中計算抵押?
