为缺少的日子填写零

时间:2016-09-15 18:46:52

标签: javascript asp.net-mvc-5

对于每天都没有数据,我想在数组中添加0: 我做的代码是错误的,因为它没有为缺少的日子添加0。 从1,2,6开始应该是1,2,3,4,5,6 - 并且有零到6的结果。结果如下。

        var i = 1;
        var found = false;

        try {
            for (var x = 0; x < @ViewBag.MonthDays; x++) {
                i = 1;
                do{
                    found = false;
                    try {
                        if ( i == cheque[x].theDay) {
                            s2.push(cheque[x].theMoney * -1);
                            found = true;
                            console.log("Day: " + cheque[x].theDay + " i " + i);
                            break
                        }
                    }
                    catch (error) {
                        s2.push(0);
                    }
                    console.log(i == cheque[x].theDay, i, cheque[x].theDay);
                    i++

                } while ((i < @ViewBag.MonthDays))
                console.log(found == false);
                if (found == false)
                    s2.push(0);
            }
        }
        catch (error){
            s2.push(0);
        }
        console.log ("Push: " + s2);

结果:

Day: 1 i 1
false
false 1 2
Day: 2 i 2
false
false 1 6
false 2 6
false 3 6
false 4 6
false 5 6
Day: 6 i 6

说日:6匹6匹配时。

我知道有一种更好的方法可以做到这一点,方法有点像这样:

items = items2.map( row => 
    //is there a matching row in items?
    items.filter( r => r.theString == row.theString).length ==  0 ? 
   //if not, fill with zeros
          {theString:0, theCount:0} : 
   //if there is, return the items' row
   items.filter( r => r.theString == row.theString)[0] );

但只是将两个数组相互匹配。这个需要每个月的每一天。

1 个答案:

答案 0 :(得分:-1)

这就是我现在的表现:

            var monthD = new Array(@ViewBag.MonthDays)
                .join().split(',')
                .map(function(item, index){ return ++index;})
            console.log (monthD);

             cheque = monthD.map( row => 
                //is there a matching row in items?
                cheque.filter( r => r.theDay == row).length ==  0 ? 
               //if not, fill with zeros
                {theDay:0, theMoney:0} : 
               //if there is, return the items' row
               cheque.filter( r => r.theDay == row)[0] );

            try {
                for (var x = 0; x < @ViewBag.MonthDays; x++) {
                    s2.push(cheque[x].theMoney * -1);
                }
            }
            catch (error){
                s2.push(0);
            }

更好更快的方法。没有所有令人困惑的循环弄乱我的想法。