我怎么能得到索引在javascript递归函数?


let array = [1, [2, 3, [4, 5, ["six", "seven", 6666, [8, 9, [10]]]]]]
//1.find last element
//2. index way like in **console.log(array[1][2][2][3][2][0]** but should print 
// [1][2][2][3][2][0] or 1,2,2,3,2,0

在这个函数中,我找到了最后一个元素,现在我找不到第二个问题(应该是递归函数)

function findLastElement (arr){
for (let element of arr ){
if(typeof element === "object"){
findLastElement(element)
console.log(element)
}
}
}
findLastElement(array)

可以使用递归函数始终取最后一个索引,如果最后一项也是数组,则继续:

const getLessIndexes = arr => {
const last = arr.length - 1

return [
last,
...Array.isArray(arr[last]) 
? getLessIndexes(arr[last]) 
: []
]
}
const array = [1, [2, 3, [4, 5, ["six", "seven", 6666, [8, 9, [10]]]]]]
const result = getLessIndexes(array)
console.log(result)

可以使用Array.entries()

function findLastElement (arr){
for (let [index, element] of arr.entries() ){
if(typeof element === "object"){
findLastElement(element)
console.log(element)
console.log(index)
}
}
}

let array = [1, [2, 3, [4, 5, ["six", "seven", 6666, [8, 9, [10]]]]]];
function findLastElement (arr){
for (let [index, element] of arr.entries() ){
if(typeof element === "object"){
findLastElement(element)
console.log(element)
console.log(index)
}
}
}
console.log( findLastElement(array) )

最新更新