简体   繁体   中英

Why does my recursive function return undefined despite using return?

When I try to recursively build an array of each parent index from an element up to body I get undefined returned.

Could someone please tell me why? I can see the expected result just fine but can't seem to return it, even though I meet the stop condition and explicitly use 'return'.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>

<body>
    <header>
        <div>Div 1</div>
        <div>Div 2</div>
        <div>Div 3</div>
        
        <nav>
            <ul>
                <li>Item 1</li>
                <li id="target">Item 2</li>
                <li>Item 3</li>
            </ul>
        </nav>
    </header>
    
    <script type="application/javascript">
        const nodeIndex = ($node = undefined) =>
            [...$node.parentNode.children].indexOf($node)

        const nodePositionFromRoot = (
            $node = undefined,
            ancestorIndexes = []

        ) => {
            ancestorIndexes = [...ancestorIndexes, nodeIndex($node)]
    
            if ($node.tagName === 'BODY') {
                console.log('ancestorIndexes', ancestorIndexes)
                return ancestorIndexes
            }
    
            nodePositionFromRoot($node.parentNode, ancestorIndexes)
        }

        const $element = document.getElementById('target')

        const elementsPosition = nodePositionFromRoot($element)

        console.log('Result:', elementsPosition)
    </script>
</body>

</html>

Well you need to add only a return statement to your recursive calling of the function

 const nodeIndex = ($node = undefined) => [...$node.parentNode.children].indexOf($node) const nodePositionFromRoot = ( $node = undefined, ancestorIndexes = [] ) => { ancestorIndexes = [...ancestorIndexes, nodeIndex($node)] if ($node.tagName === 'BODY') { console.log('ancestorIndexes', ancestorIndexes) return ancestorIndexes } // this return statement is required to pass the ancesstorIndexes from the last call to the previous and so on untill the first call ends and returns the result return nodePositionFromRoot($node.parentNode, ancestorIndexes) } const $element = document.getElementById('target') const elementsPosition = nodePositionFromRoot($element) console.log('Result:', elementsPosition)
 <header> <div>Div 1</div> <div>Div 2</div> <div>Div 3</div> <nav> <ul> <li>Item 1</li> <li id="target">Item 2</li> <li>Item 3</li> </ul> </nav> </header>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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