递归函数返回未定义而不是预期的“ ... px”字符串值

时间:2019-07-08 03:07:41

标签: javascript recursion

我有一个函数,它递归地遍历元素的子元素,直到找到非值"normal"的行高并返回该值。不幸的是,即使它确实找到了非undefined的值,它仍然继续返回normal。我是否误解了递归函数的工作原理?

function getLineHeight($el) {
    const styles = window.getComputedStyle($el);
    console.log("\n");
    console.log("$el :", $el);
    const lineHeight = styles["line-height"];
    console.log("lineHeight :", lineHeight);
    if (lineHeight === "normal") {
        const $child = $el.children[0];
        console.log("$child :", $child);
        if ($child instanceof HTMLElement) {
            console.log("is HTMLElement");
            getLineHeight($child);
        } else {
            // Make a best guess of what the line height should be (1.15) if the
            // computed styles never returns anything that is not line-height:
            // "normal".
            return _.toInteger(_.trimEnd(styles["font-size"], "px")) * 1.15;
        }
    } else {
        console.log(`return lineHeight: ${lineHeight}`);
        return lineHeight;
    }
}

console.log('final getLineHeight():', getLineHeight($element));

记录的内容

$el : <div class=​"vertical-spacing bottom-small-x">​…​</div>​
lineHeight : normal
$child : <p class=​"typography-text p1-bold">​Information that you provide voluntarily​</p>​
is HTMLElement


$el : <p class=​"typography-text p1-bold">​Information that you provide voluntarily​</p>​
lineHeight : 24px
return lineHeight: 24px
final getLineHeight(): undefined

0 个答案:

没有答案