JS类转换功能 [英] JS category conversion function

查看:98
本文介绍了JS类转换功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

集团类别转换

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 )到字符串包含它等于类的名称(数组对象自动)。


I'm trying to use a loop within a loop in combination with a multi-dimensional array to achieve a neat conversion function from a group (string new_auto) to a string equal to the name of the category containing it (array object Auto).

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

推荐答案

动态项目去分类功能

由于在意见建议的Palmsey,这是通过一个环中之环和多维数组的组合,发现对象的父类的正确方法。

As suggested by Palmsey in the comments, this is the proper way of discovering an object's parent category through the combination of a loop-within-a-loop and a multidimensional array.

//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!");
}

我选择了替代上述这种方法,因为它是动态的。只要通过不断的模式,我们可以将项目的值转换成他们所属的组,反之亦然,组配任何复杂性。

I chose this method above the alternatives because it's dynamic. Simply by continuing the pattern, we can convert the values of items to the groups that they belong to, and vice-versa, with any level of group complexity.

这篇关于JS类转换功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆