为什么我传递给函数的参数未定义
Why is the parameter I am passing to my function undefined?
我使用的是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
相关文章:
- 要求未定义JS回调参数
- 为什么grunt contrib connect的中间件选项的第三个参数是未定义的
- 角度指令控制器:参数不是函数,未定义
- AngularJS-参数'菜单Ctrl'不是函数,未定义
- JS和Jquery函数参数未定义
- 为什么我传递给函数的参数未定义
- Javascript-函数获取数组元素参数未定义/为null
- 使用原型向函数添加属性会导致函数参数未定义
- 传递给闭包的角度参数未定义
- 骨干路由器多参数;第二个参数未定义
- Express.js请求参数未定义
- 数组中.按对象属性筛选,参数未定义
- jQuery和javascript表单验证:密码字段参数未定义,密码确认ok
- JQuery高亮插件,参数未定义
- Express JS:参数未定义
- 函数参数未定义
- Javascript:参数未定义
- 使用$stateParams, UI-router从URL获取参数.未定义的值
- ng-table's getData函数中参数未定义
- 获取“参数未定义”;在jQuery与AJAX, MySQL和PHP