jQuery在多维数组中查找/设置对象时遇到麻烦

时间:2016-12-16 17:59:18

标签: javascript jquery arrays multidimensional-array associative-array

我正在尝试使用jquery循环选择并从值中创建一个二维数组:

使用下面的代码我想要的输出将如下所示:

object {Monday => hours[0] = '1a-2a',hours[1] = '2a-3a', Tuesday => hours[0] = '4p-5p', hours[1] = '5p-6p'}

假设我的.each选择器看起来像这样:

<ol id='selectable'>
   <li data-day='Monday' data-time='1a-2a' class='ui-selected'></li>
   <li data-day='Monday' data-time='2a-3a' class='ui-selected'></li>
   <li data-day='Tuesday' data-time='4p-5p' class='ui-selected'></li>
   <li data-day='Tuesday' data-time='5p-6p' class='ui-selected'></li>
</ol>

我试图使用下面的代码来获得我想要的输出,我一直收到错误消息:

“TypeError:无法使用'in'运算符在undefined(...)中搜索'hours'”

var days = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
var selection = [];
var i;
    for (i = 0; i < days.length; ++i) {
        $( ".ui-selected", "#selectable" ).each(function() {
            if($(this).attr( 'data-day' ) == days[i]){
                if(!(days[i] in selection)){
                    selection.push(days[i]);
                    if(!("hours" in selection[days[i]])){
                        selection[days[i]] = {hours:[]};
                    }
                }
                selection[days[i]]['hours'].push($(this).attr( 'data-time' ));
            }
        });
        console.log(selection);
    }

知道我在这里做错了吗?

1 个答案:

答案 0 :(得分:1)

您需要selection作为对象,而不是数组,如下所示:

var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var selection = {};
var i;
for (i = 0; i < days.length; ++i) {
    $( ".ui-selected", "#selectable" ).each(function() {
        if($(this).data( 'day' ) == days[i]){
            if(!(days[i] in selection)){
                selection[days[i]] = {};
                if(!("hours" in selection[days[i]])){
                    selection[days[i]] = {hours:[]};
                }
            }
            selection[days[i]]['hours'].push($(this).data( 'time' ));
        }
    });
    console.log(selection);
}

在这里工作小提琴:https://jsfiddle.net/wehdnm20/1/