JS类转换功能(JS category conversion function)

2019-10-30 10:45发布

集团类别转换


var Auto = ['new_auto', 'add_auto'];
//more category objects 

var categories = [Auto, Fire, Health, Life, Bank];

function groupToCat(group) {

    for (x = 1; x < categories.length; x++) {
        for (i = 1; i < categories[x].length) {
            if (group == categories[x][i]) {
                return categories[x]
            }
        }
    }
}

我试图在组合使用循环回路内的一个多维阵列,以从一组(串实现整齐转换功能new_auto )到等于包含它(阵列对象的类别的名称的字符串Auto )。


但因为它是,我回来了类对象,而不是它的名称。 我怎样才能做到这一点?

Answer 1:

动态项目“去分类”功能


作为评价建议的Palmsey,这是通过一个循环中之环和一个多维阵列的组合发现对象的父类的适当的方式。

//Define Category Names and Children

var Auto = {
    name: 'Auto',
    items: ['new_auto', 'add_auto']
};

var Fire = {
    name: 'Fire',
    items: ['new_fire', 'add_fire']
};

var Health = {
    name: 'Health',
    items: ['health']
};

//Bring each category into a single array

var categories = [Auto, Fire, Health, Life, Bank];

//Because of the complimentary nature of loops and arrays, we can
//access each additional dimension of the array with an additional
//loop dimension.

function groupToCat(group) {

    for (x = 0; x < categories.length; x++) {
        for (i = 0; i < categories[x].items.length; i++) {
            if (group == categories[x].items[i]) {
                return (categories[x].name);
            }
        }
    }

    return ("No match found!");
}

我选择了替代上述这种方法,因为它是动态的。 只要通过持续的模式,我们可以将项目的值转换为它们所属的组,反之亦然,以组任意复杂程度。



文章来源: JS category conversion function