【问题标题】:AS3: count items in an array element, then add them back into the arrayAS3:计算数组元素中的项目,然后将它们添加回数组
【发布时间】:2014-02-28 01:56:37
【问题描述】:

我的目标是采用如下所示的数组:

    [{"ct_start_year":"2013","ct_start_month":"07", ct_prog: "1"},     
    {"ct_start_year":"2013","ct_start_month":"07", ct_prog: "2"},
    {"ct_start_year":"2013","ct_start_month":"08", ct_prog: "1"},
    {"ct_start_year":"2012","ct_start_month":"03", ct_prog: "1"},
    {"ct_start_year":"2012","ct_start_month":"04", ct_prog: "1"}]

然后编写一个循环,识别每年(“ct_start_year”)中的程序(“ct_prog”),评估月份(“ct_start_month”),如果该月有超过1个程序,则将它们加在一起以产生一个如下所示的新数组:

    [{"ct_start_year":"2013","ct_start_month":"07", ct_prog: **"3"**}, 
{"ct_start_year":"2013","ct_start_month":"08", ct_prog: "1"},
    {"ct_start_year":"2012","ct_start_month":"03", ct_prog: "1"},
    {"ct_start_year":"2013","ct_start_month":"04", ct_prog: "1"}]

如您所见,此示例中的其中一行已“消失”,因为值为 1 和 2 的“ct_prog”变为 3,因为该年(“2013”​​)的月份相同(“07”) .如果该月只有一个节目,例如 2012 年,则该行保持不变。

这是我到目前为止所做的:

for (var i:int = 0; i<date_test.length; ++i) {

      if (date_test[i].ct_prog >= 1 && date_test[i].ct_start_year == "2013"){

        if (date_test[i].ct_start_month == date_test[i].ct_start_month){

        trace (date_test[i].ct_prog + date_test[i].ct_start_year + date_test[i].ct_start_month);   
    }
    }

但是跟踪的结果并不令人满意,因为在“2013”​​的情况下,不仅“07”月份的程序返回,“08”月份的程序也返回 - 我希望第二个"if" 语句至少会过滤掉它。

此外,我仍然不确定如何 1) 在 ct_prog 元素中添加“07”月份的值,以在新数组中生成“3”值;以及 2) 如何将该值添加到新数组中并消除数组中现在不需要的“额外”行。

任何帮助,非常感谢,一如既往!

【问题讨论】:

    标签: arrays actionscript-3 loops for-loop


    【解决方案1】:

    解决这个问题的最佳方法是使用哈希表或类似的东西。

    您可以让您的“键”为 ct_start_year + ct_start_month(串联为一个超级简单的字符串),您的“值”应该是您可以使用该键找到的所有值的“加法”。

    代码如下:

    {
        var dict:Dictionary = new Dictionary();
    
        for(var i:uint = 0; i < date_test.lenght; ++i)
        {
            var key:String = date_test[i].ct_start_year + date_test[i].ct_start_month;
    
            if (dict[key] == null)
              dict[key] = 0;
    
            dict[key] += date_test[i].ct_prog
        }
    }
    

    这种数据结构对解决此类问题有很大帮助(您有一个易于识别的键来分组对象或值)。

    【讨论】:

    • 谢谢!我已经看到了字典和地图的实现,所以我对这可能是一个解决方案并不感到惊讶。我会试试看!
    猜你喜欢
    • 2016-08-18
    • 1970-01-01
    • 1970-01-01
    • 2015-06-28
    • 1970-01-01
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多