在数组中添加/删除对象,并检查对象是否已退出

Adding/removing an object into array and also check if object already exits

本文关键字:对象 检查 是否 退出 添加 删除 数组      更新时间:2023-09-26

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

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);
    }
},

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

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.
            }
        }
    }
},

indexId 在 else if block 中未定义