为什么我传递给函数的参数未定义

Why is the parameter I am passing to my function undefined?

本文关键字:参数 未定义 函数 为什么      更新时间:2023-09-26

我使用的是typeahead.js,下面是代码:

<script>
    $(function () {
        var projectNumbers;
        $.getJSON("api/Project/GetAllNumbers")
            .done(function (result) {
                console.log(result);
                projectNumbers = result;
            })
            .fail(function (jqXHR, textStatus, err) {
                alert('Error: ' + err);
            });
        var substringMatcher = function (strs) {
            return function findMatches(q, cb) {
                var matches, substrRegex;
                console.log(strs); // Undefined
                console.log(projectNumbers); //Filled
                // an array that will be populated with substring matches
                matches = [];
                // regex used to determine if a string contains the substring `q`
                substrRegex = new RegExp(q, 'i');
                // iterate through the pool of strings and for any string that
                // contains the substring `q`, add it to the `matches` array
                $.each(strs, function (i, str) {
                    if (substrRegex.test(str)) {
                        // the typeahead jQuery plugin expects suggestions to a
                        // JavaScript object, refer to typeahead docs for more info
                        matches.push({ value: str });
                    }
                });
                cb(matches);
            };
        };
        $('#jobNumber').typeahead({
            hint: true,
            minLength: 3,
            highlight: true,
        },
          {
              name: 'projects',
              source: substringMatcher(projectNumbers),
          });
    });
</script>

如果您查看substringMatcher函数,则参数strs是未定义的。我把它放在预编源代码的底部。projectNumbers在我将数据传递给函数时就有数据,甚至在我将其记录到控制台时,它也有数据。但是strs是未定义的。

有什么建议吗?

更新

当我加载页面时,我会记录getJSON的返回,并填充它(第7行)。如果它被填充了,为什么当我把它作为参数传递时它不被填充呢?

这是因为您的代码是异步的。您的getJSON done()将在代码的其余部分之后执行。所以当你执行时

source: substringMatcher(projectNumbers)

projectNumbers可能尚未初始化。但是,当您调用substringMatcher(projectNumbers)创建的函数时,projectNumbers将被初始化。这就是为什么你得到:

console.log(strs); // Undefined console.log(projectNumbers); //Filled