После удаления элементов со сращиванием, есть неопределенный материал - PullRequest
0 голосов
/ 14 октября 2019

Итак, я хочу удалить элементы массива, используя splice

custom_boxes_exist.splice($.inArray(id, custom_boxes_exist),1);
custom_boxes_order.splice($.inArray(id, custom_boxes_order),1);
box_content.splice($.inArray(id, box_content),1);

Когда при выводе содержимого массива после использования соединения я получаю этот вывод:

Array(5) [ "Content of box with id 0", undefined, undefined, undefined, "Content of box with id 4" ]

Каким-то образомон удаляет элементы, и почему-то это не так.

Вы можете видеть это, когда добавляете ящик, удаляете его, а затем добавляете новый

var custom_box_id = 0;
var custom_boxes_order = [];
var custom_boxes_exist = [];
var box_content = [];


function addNewBox() {
  reOrderArray();
  custom_boxes_exist.push(custom_box_id);
  custom_boxes_order[custom_box_id] = 1;
  box_content[custom_box_id] = "Content of box with id " + custom_box_id;
  console.log("adding new box: with id " + custom_box_id);
  console.log(custom_boxes_order);
  console.log(custom_boxes_exist);
  console.log(box_content);
  $("#custom_boxes").prepend('<div id="box_' + custom_box_id + '" class="box">' + box_content[custom_box_id] + ' <span style="float:right;"><button onclick="changeOrder(' + custom_box_id + ',"up")">[UP]</button><button onclick="changeOrder(' + custom_box_id + ',"down")">[DOWN]</button><button onclick="deleteCustomBox(' + custom_box_id + ')">[x]</button></span></div>');
  custom_box_id++;
}

function changeOrder(id) {
  //
}

function reOrderArray() {
  $.each(custom_boxes_order, function(key, value) {
    custom_boxes_order[key] = value + 1;
  });
}

function testDel(id) {
  $.each(custom_boxes_exist, function(key, value) {
    if (value == id) {
      custom_boxes_exist.splice($.inArray(id, custom_boxes_exist), 1);
      return;
    }
  });
}

function deleteCustomBox(id) {
  $("#box_" + id).remove();
  custom_boxes_exist.splice($.inArray(id, custom_boxes_exist), 1);
  custom_boxes_order.splice($.inArray(id, custom_boxes_order), 1);
  box_content.splice($.inArray(id, box_content), 1);
}
.box {
  margin-top: 10px;
  padding: 10px;
  border: 1px solid black;
  border-color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<center><button onclick="addNewBox()">add new box</button></center>
<div id="editor_header" class="box">HEADER</div>
<div id="custom_boxes"></div>
<div id="editor_bottom" class="box">FOOTER</div>

1 Ответ

2 голосов
/ 14 октября 2019

Это не из-за splice(). Это связано с тем, как вы добавляете в массивы после удаления элементов. Вы делаете:

box_content[custom_box_id] = "Content of box with id "+custom_box_id;

custom_box_id с шагом каждый раз, когда вы создаете новый ящик. Если вы создаете блоки 0, 1 и 2, массив содержит

box_content[0] = "Contents of box with id 0"
box_content[1] = "Contents of box with id 1"
box_content[2] = "Contents of box with id 2"

и custom_box_id теперь 3.

Если вы удалите блок 1теперь массив содержит:

box_content[0] = "Contents of box with id 0"
box_content[1] = "Contents of box with id 2"

Обратите внимание, что индексы массива больше не соответствуют идентификаторам в содержимом.

Когда вы добавляете следующее поле, у вас теперь есть

box_content[0] = "Contents of box with id 0"
box_content[1] = "Contents of box with id 2"
box_content[3] = "Contents of box with id 3"

Обратите внимание, что box_content[2] нет, потому что custom_box_id было 3. Когда вы просматриваете весь массив, этот отсутствующий элемент отображается как undefined.

. Если вы не хотите использовать эти пробелы, вы должны использовать push(), чтобы добавить в массив, а не назначать конкретному индексу,Вы делаете это для массива custom_boxes_exist, но не custom_boxes_order и box_contents.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...