简体   繁体   中英

How to check which argument has been passed to a function

I'd like to make a call to another jQuery function and pass another argument - the argument I pass depends on the name of the argument that was passed to the original function. So i might have something like this:

matchedNumbers1 = compareArrays(userNumbers, winningNumbers1, matchedNumbers1);
matchedNumbers2 = compareArrays(userNumbers, winningNumbers2, matchedNumbers2);
matchedNumbers2 = compareArrays(userNumbers, winningNumbers3, matchedNumbers2);

//COMPARE INPUTTED ARRAY OF NUMBERS TO WINNING ARRAYS OF NUMBERS
    function compareArrays (userInput, winningNums, matches) {
        matches = 0;
        allMatchedNumbers.length = 0;
        $(userInput).each(function(i) {
            $(winningNums).each(function(j) {
                if (userInput[i] == winningNums[j]) {
                    allMatchedNumbers[matches] = userInput[i];
                    matches++;
                }
            });
        });
        switch (winningNums) {
            case 'winningNumbers1':
                alert("!!!!!");
                markMatches(ListItems1);
                break;
            case 'winningNumbers2':
                markMatches(ListItems2);
                break;
            case 'winningNumbers3':
                markMatches(ListItems3);
                break;
        }
        return matches;
    }

Hopefully the code above makes it clear what i'm trying to do. I tried using a switch statement but this only compares the value and not the name of the original argument that was passed to the function. Any help would be appreciated.

You shouldn't be doing that, even if you could. Just pass in the array that you want to match against as another argument:

function compareArrays(userInput, winningNums, matches, listToMark) {
    ...

    markMatches(listToMark)
}
function winningNumbers1(){
    var result = 1;
    return {result:result, fname: 'winningNumbers1'};
}

function winningNumbers2(){
    var result = 2;
    return {result:result, fname: 'winningNumbers2'};
}

function compareArrays (userInput, winningNums, matches) {
    var result = winningNums ? winningNums() : null;
    if(result)
    switch(result.fname){
        case 'winningNumbers1': 
        // action
            break;
        case 'winningNumbers2': 
        // action
            break;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM