0

Is it possible to design a function that has an array like the below and use an if statement to check if the type is equal to the following in any of my categories in my array below and return its associate category code?

Example:

function CheckCategory(type) {

array = 

[NOTES, CAT-A],
[BOOKS, CAT-B],
[MUSIC, CAT-C],
[SOFTWARE, CAT-D]

if (type == "NOTES") { return "CAT-A" }


}
4

3 回答 3

1

关于什么

var CatTable={"NOTES": "CAT-A", "BOOKS": "CAT-B", "MUSIC": "CAT-C", "SOFTWARE": "CAT-D"};

function  CheckCategory(type) {
  if (CatTable[type]) return CatTable[type];
  else return "UNKNOWN CATEGORY"
}
于 2013-11-07T18:29:06.523 回答
0
function CheckCategory(type) {
    var data = [
        ['NOTES', 'CAT-A'],
        ['BOOKS', 'CAT-B'],
        ['MUSIC', 'CAT-C'],
        ['SOFTWARE', 'CAT-D']
    ];

    for( i = 0; i < data.length; i++) {
        if (data[i][0] == type) {
            return data[i][1];   
        }
    }

    return "Not found";
}

http://jsfiddle.net/Mansfield/5s8wr/2/

于 2013-11-07T18:27:52.433 回答
0

您可以将array变量声明为二维数组(数组数组):

function checkCategory(type) {
    var array = [
        ['NOTES', 'CAT-A'],
        ['BOOKS', 'CAT-B'],
        ['MUSIC', 'CAT-C'],
        ['SOFTWARE', 'CAT-D']
    ];

    // Then, simply loop over your array and check for the type
    for (var i = 0; i < array.length; i++) {

        if (type == array[i][0]) {

            // It will return the CAT-X of the matching type
            return array[i][1];
        }
    }
}

此外,您可以将变量声明为对象,并返回type属性值:

function checkCategory(type) {
    var values = {
        NOTES: 'CAT-A',
        BOOKS: 'CAT-B',
        MUSIC: 'CAT-C',
        SOFTWARE: 'CAT-D'
    }

    return values[type];
}
于 2013-11-07T18:31:57.137 回答