除非你newSuggested
在代码的上面某处声明了,否则它是窗口上的一个全局变量(这不是问题,只是指出来)。
它在您记录它的位置未定义的原因是因为当该console.log
语句运行时,提取尚未完成。
无论你要做什么newSuggested
,你都需要在complete
回调函数中完成。
// declare the variable using var, so it is not global
var newSuggested;
cars.fetch().complete(function(){
newSuggested = cars.models.filter(function (model) {
return _.contains(model.attributes.suggestedTo, storedVin)
});
console.log(newSuggested); // works!
// do something with newSuggested here, hard to tell what you are trying to do.
probablyUpdateViewInSomeWay(newSuggested);
});
// fetch not complete here!
// this is not a scope problem, but an async problem.
// complete callback has not been called yet.
console.log(newSuggested) //undefined, this is expected
旁注:complete
在 jQuery 1.8 中已弃用,因此您应该done
改用。