使用.shift()更新数组元素

时间:2015-08-11 16:46:30

标签: javascript function

我正在努力解决一个非常简单的问题,但我一直在反复思考,似乎无法弄明白该做什么。

http://jsbin.com/harokap/edit?js,output

var parkRides = [["Bumbling Boats", 20], ["Scary Cyclone", 45], 
["Cloudy Crevase", 10], ["Crazy Crapshoot", 5]];

var fastPassQueue = ["Crazy Crapshoot", "Cloudy Crevase", "Bumbling Boats",
    "Crazy Crapshoot"];

function writeTicket(allRides,passRides,pick){
    if(pick == passRides[0]){
        passRides.shift();
        return function(){
            alert("Lucky you! You got a Fast Pass to " + pick + "!");
        };
    }else{
        for(var i = 0; i < allRides.length; i++){
            if(pick == allRides[i][0]){
                return function(){
                    alert("Now printing ticket for " + pick + ". Your wait time is about " + allRides[i][1] + " minutes.");
                };
            }
        }
    }
}

var rideChoice = "Crazy Crapshoot";

var ticket = writeTicket(parkRides,fastPassQueue,rideChoice);

ticket();

在该代码中,我有一个名为&#34; fastPassQueue&#34;的数组。我想用&#34; writeTicket&#34;中的passRides.shift()更新功能

我希望writeTicket能够识别每次运行函数时都从fastPassQueue中删除了第一个元素(并在第一次调用函数后运行else条件),但我无法弄清楚如何去做吧。我尝试将fastPassQueue添加到函数的开头,如果我首先以原始方式运行函数然后将其添加到函数中,那么我将无法将其添加到函数中,但我无法弄清楚如何使函数从启动...

提前感谢您的任何反馈。

1 个答案:

答案 0 :(得分:0)

就像在for循环中不返回函数一样简单,改为创建字符串,并始终返回函数

var parkRides = [
    ["Bumbling Boats", 20],
    ["Scary Cyclone", 45],
    ["Cloudy Crevase", 10],
    ["Crazy Crapshoot", 5]
];

var fastPassQueue = ["Crazy Crapshoot", "Cloudy Crevase", "Bumbling Boats", "Crazy Crapshoot"];

function writeTicket(allRides, passRides, pick) {
    if (pick == passRides[0]) {
        passRides.shift();
        return function () {
            alert("Lucky you! You got a Fast Pass to " + pick + "!");
        };
    } else {
        var match = "";

        for (var i = 0; i < allRides.length; i++) {
            if (pick == allRides[i][0]) {
                match = "Now printing ticket for " + pick + ". Your wait time is about " + allRides[i][1] + " minutes.";
            }
        }

        return function () {
            alert(match);
        };
    }
}

var rideChoice = "Bumbling Boats";

var ticket = writeTicket(parkRides, fastPassQueue, rideChoice);

ticket();

FIDDLE