我是 JavaScript 新手,正在从在线教程中学习它。当前表达式是关于函数表达式的使用,特别是 - 从函数内部返回函数表达式。
这是代码:
//array of all available rides, with respective wait times
var parkRides = [["Birch Bumpers", 40], ["Pines Plunge", 55], ["Cedar Coaster", 20], ["Ferris Wheel of Firs", 90]];
//array of fast pass rides, indicating next up ride
var fastPassQueue = ["Cedar Coaster", "Pines Plunge", "Birch Bumpers", "Pines Plunge"];
//function to build fast pass queue using array
function buildTicket(allRides, passRides, pick) {
//if user has picked the first ride in fast pass queue, alert so...
if(pick == passRides[0]) {
//remove first item from queue using shift and store it in a var
var pass = passRides.shift();
//return function expression here
return function () {
alert("QuicK!! You've got a fast pass to " + pass + "!");
}; //return ends with a ;
}
else {
for (var i = 0; i < allRides.length; i++) {
if(pick == allRides[i][0]) {
//return a function expression here
return function () {
alert("A ticket is printing for " + allRides[i][0] +"!\n"+ " Your wait time is about " + allRides[i][1] + " minutes.");
};
}
}
}
}
//use function buildticket
var wantsRide = "Pines Plunge";
var ticket = buildTicket(parkRides, fastPassQueue, wantsRide);
//execute function expression by calling ticket()
ticket();
我正在使用 MS Visual Studio Code,在代码结束时,我收到一个错误和一个警告,即使代码成功运行,并且我根据wantsRide
变量获得所需的结果。但是,我无法理解错误和警告的原因。
在屏幕底部(下面的屏幕截图),我得到 1 个十字和 1 个感叹号图标,我认为这意味着 1 个错误和 1 个警告。
但是当我点击它时,我会在栏的顶部看到一个突出显示的区域,上面写着! Function inside loop
这些行被突出显示:
return function () {
alert("A ticket is printing for " + allRides[i][0] +"!\n"+ " Your wait time is about " + allRides[i][3] + " minutes.");
};
这里似乎有什么问题?我知道它是for
循环内的函数表达式,但为什么会生成警告?是不是因为该if(pick==allRides[i][0])
语句可能永远不会为真,所以函数表达式永远不会被执行?