This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center
                            
                        
                    
                
                7年前关闭。
            
        

在下面的代码中,我无法从函数中访问“颜色”,但可以访问“ numColors”。 getColors()函数似乎可以正确设置数组,但是init()函数无法访问它,如alert语句结果所示。

可以使用诸如“?colors = 0000FF | FF0000”之类的参数字符串来调用该页面。

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

<head></head>

<body>

<script>

( function () {

        var colors = [];
        var numColors;

        document.addEventListener("DOMContentLoaded", init, false );

        function init() {
            colors = getColors()

            alert(numColors);
            alert(colors);
        }

        function getColors() {
            var data = getURLParameter('colors');
            var list = data.split('|');

            for (i = 0; i < list.length; i++) {
                colors.push(list[i]);
            }

            numColors = colors.length;

            alert(numColors);
            alert(colors);
        }


        // from http://www.netlobo.com/url_query_string_javascript.html

        function getURLParameter(name) {
            name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");

            var regexS = "[\\?&]" + name + "=([^&#]*)";
            var regex = new RegExp( regexS );

            var results = regex.exec( window.location.href );

            if (results == null) {
                return "";
            } else {
                return results[1];
            }
        }

} ) ();

</script>

</body>
</html>

最佳答案

getColors在运行时修改colors,然后用colors的返回值覆盖getColors(),该返回值(由于缺少return语句)为undefined

删除任务:

function init() {
    getColors()


或更改getColors,使其使用局部变量,然后将其返回。

10-05 19:03