【问题标题】:Max Stack exceeded error, how would I fix this?最大堆栈超出错误,我将如何解决这个问题?
【发布时间】:2018-06-06 08:12:35
【问题描述】:

如果外部函数中的数字在内部函数列表中,我正在创建一个返回 true 的函数

<script>
function hasMatch(item) {
    hasMatch(2)  
    function inList() {
        var List = [1,2,3,4];
        for (i = 0; i<List.length; i++){
            if (list[i] == item) { 
                return true; 
            } else {
                return false;
            }
        }
    }
    inList();
}
hasMatch();
</script>

我收到“超出最大堆栈错误”,我该如何解决?

【问题讨论】:

    标签: javascript recursion stack-overflow


    【解决方案1】:

    hasMatch(2) 是没有任何终止条件的递归调用。

    hasMatch() 被无限调用,这就是为什么您会看到堆栈超出错误。

    function hasMatch(item) { 
        function inList() {
            var List = [1,2,3,4];
            for (i = 0; i<List.length; i++){
                if (List[i] == item) { 
                    return true; 
                } else {
                    return false;
                }
            }
        }
        return inList();
    }
    
    hasMatch(2);
    

    【讨论】:

    • 如何以及在哪里添加终止​​条件?
    猜你喜欢
    • 2017-07-06
    • 1970-01-01
    • 2015-10-10
    • 2023-03-30
    • 2021-05-21
    • 2013-08-20
    • 1970-01-01
    • 2011-08-31
    • 1970-01-01
    相关资源
    最近更新 更多