将对象添加/删除到数组中,还检查对象是否已存在

时间:2013-02-01 12:54:53

标签: javascript extjs sencha-touch

我有一个任务,我需要将对象推入一个数组,然后才需要检查对象是否已经退出,如果需要从数组中删除/删除对象。 我已经编写了示例代码,但我没有按预期获得输出。

optionlistItemTap : function (data, index) {
    var record = data.getStore().getAt(index);
    var Id = record.raw.id;
    var arraysize = names.length;

    for (i = 0; i <= arraysize; i++) {
        if (arraysize == 0) {
            names.push(record);
            var indexId = names[i].raw.id
            var Id = record.raw.id
            break;
        }
        else if (indexId == Id) {
            names.splice(i, 1);
            break;
        }
        else
        names.push(record);
    }
},

2 个答案:

答案 0 :(得分:1)

看看你的代码,我最好的猜测是你需要这个:

optionlistItemTap : function (data, index) {
    var record = data.getStore().getAt(index); // Get the record
    var Id = record.raw.id;                    // Get the record's id
    var arraysize = names.length;              // Get the length of the `names` array

    if (arraysize == 0) {                      // If the `names` array is empty,
        names.push(record);                    // Push the record to the array.
        return;                                // Break out of the function.
    }else{                                     // Otherwise,
        for (var i = 0; i <= arraysize; i++) { // Loop through the array,
            if (names[i].raw.id == Id) {       // And if names[i]'s id matches the id of the element to add,
                names.splice(i, 1, record);    // Replace the element in `names` with the record.
                return;                        // Break out of the function.
            }
        }
    }
},

答案 1 :(得分:0)

如果块

indexId在else中未定义