【问题标题】:JS category conversion functionJS类别转换功能
【发布时间】:2014-03-18 21:53:19
【问题描述】:

组到类别转换


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)。


但实际上,我返回的是类别对象,而不是它的名称。我该怎么做?

【问题讨论】:

  • 这就是你想要的吗? stackoverflow.com/questions/1009911/…
  • @Kirby ...这几乎很有趣。在您可以“几乎”做任何您可以想象的事情的语言中,您不能将对象转换为包含代表它的名称的字符串。好吧,这只是我的运气。
  • 与其尝试返回变量名 (Auto),我建议您将类别名称作为对象的属性并返回。 var Auto = { name: 'Auto', items: ['new_auto', 'add_auto'] }; 然后return categories[x].name。另外,我认为在遍历这些数组时,您需要从 0 开始,而不是 1。
  • @palmsey 哦,完美的解决方案。是的。新手错误。

标签: javascript arrays loops


【解决方案1】:

动态物品“去分类”功能


正如 Palmsey 在 cmets 中所建议的,这是通过循环内循环和多维数组的组合来发现对象的父类别的正确方法。

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

我在替代方法之上选择了这种方法,因为它是动态的。只需继续该模式,我们就可以将项目的值转换为它们所属的组,反之亦然,具有任何级别的组复杂性。

【讨论】:

    猜你喜欢
    • 2020-06-23
    • 2018-03-05
    • 2020-07-11
    • 2021-09-30
    • 1970-01-01
    • 1970-01-01
    • 2020-12-02
    • 2011-12-14
    • 2020-02-08
    相关资源
    最近更新 更多