将全局数组更新为函数

时间:2015-06-19 13:10:51

标签: javascript global-variables

我们首先构建一个JQuery UI Datepicker。后来我们想更新(refesh)这个。我们突出显示一些带颜色的日期,我们希望通过此刷新来改变颜色。我们构建一个带有彩色日期的数组,我们希望在更新此数组后更新此数组刷新=>但更新不起作用!为什么呢?

<script type="text/javascript">
    var dates = {'2015/5/5':'highlight_red','2015/5/6':'highlight_red'};

    function refreshCalendar (date, prozent) {
        var year = date.getFullYear();
        var month = date.getMonth();
        var day = date.getDate();   
        var search = year+'/'+month+'/'+day;
        if (search in dates) {
            if (prozent == 100) {
                dates[search] = 'highlight_green';
            } else {
                dates[search] = 'highlight_red';
            }
        }
    }

    refreshCalendar ('2015/5/5',100);

    var erg;
    for (elem in dates) {
        erg += elem+" => "+dates[elem];
    }
    alert(erg);
</script>

我们用魔杖将日期2015/5/5从红色变为绿色,但阵列讨厌这个更新;-)在控制变量erg中运行funktion之后是相同的

2 个答案:

答案 0 :(得分:0)

您将日期作为字符串传递,但在refreshCalendar中,您将其视为Date对象。

尝试更改

refreshCalendar ('2015/5/5', 100);

refreshCalendar (new Date('2015/5/5'), 100);

答案 1 :(得分:0)

jsFiddle

描述:添加了日期解析并初始化了erg变量,以便不返回undefined。

var dates = {'2015/5/5':'highlight_red','2015/5/6':'highlight_red'};

// parse a date in yyyy/mm/dd format
function parseDate(input) {
    var parts = input.split('/');
    // new Date(year, month [, day [, hours[, minutes[, seconds[, ms]]]]])
    return new Date(parts[0], parts[1]-1, parts[2]); // Note: months are 0-based
}

function refreshCalendar (date, prozent) {
    //we have to parse out the date (real date object)
    var parsedDate = parseDate(date);
    var year = parsedDate.getFullYear();
    var month = parsedDate.getMonth();
    var day = parsedDate.getDate();   
    var search = year+'/'+month+'/'+day;
    if (search in dates) {
        if (prozent == 100) {
            dates[search] = 'highlight_green';
        } else {
            dates[search] = 'highlight_red';
        }
    }
}

refreshCalendar ('5/5/2015', 100);
// you have to initialize erg since you are using += as it will return undefined on first pass
var erg = '';
for (elem in dates) {
    erg += elem + " => " + dates[elem];
}
alert(erg);