Javascript сдвиг и замена значения при условии - PullRequest
1 голос
/ 09 марта 2020

У меня есть массив со значениями:

[1,2,3,4,5,6,7,8,9]

, если активируется изменением выбора опции, скажем, я выбираю опцию, значение которой равно « istirahat » во 2-й строке, затем становится пустой строкой, но после пустой строки число сохраняется в последовательности, как на моем скриншоте:

enter image description here

в этом случае это решается с помощью этой функции:

 function add(array, index, value) {
        array.splice(index, 0, value);
 }

функция выше работает так, как я ожидал:

1
-
2
3
4
5
6
7
8

НО у меня новый случай, что если я выберу опцию со значениями " pelajaran ", то пропущенное число вернется и заменит пустую строку, я попробую этот скрипт:

 $(document).on('change','.jenis_mapel', function(event) {
   event.preventDefault();
    if ($(this).val() == "istirahat") //get val of select option (istirahat condition)
    {
        add(arr,index,'')
        var col1;
        var num = 0;

        $('.tb_senin tr').find('td:eq(0)').each(function() { //loop the arr value to first column (jam ke column)
            col1 = $(this).text(arr[num]);
            num++;
        });

        console.log(arr);
    }
    else //(other condition, that the number should be back)
    {
        var tbRow = $('.tb_senin tr').length - 1;
        if (arr[index] == "") {
            arr.splice(index, 1);
        }
        console.log(arr);
    }
});

Ошибка, когда я выбираю " istirahat " во 2-й строке и 3-й строке, массив будет выглядеть так:

[1, " "," ", 2, 3, 4, 5, 6, 7, 8, 9]

когда я удалил индекс 1, это стало так (что я выбрал вариант pelajaran во 2-м ряду, индекс 1 ар луч): [1, "", 2, 3, 4, 5, 6, 7, 8, 9]

Какой результат я ожидал получить следующим образом:

1 
2
""
3
4
5
6
7
8

Кто-нибудь может мне помочь?

1 Ответ

1 голос
/ 09 марта 2020

Я наконец понял вашу проблему.

Вот ваш воспроизведенный баг:

var arr = [1,2,3,4,5,6,7,8,9];

// You click on the second row and one empty item is added.
var clickedIndex1 = 1;
add(arr, clickedIndex1, '');
log(arr);

// Now when you click a different row you are checking if 
// the row contains empty string and if is the case ONLY then 
// you will remove the empty string. This is the BUG
var clickedIndex2 = 3;
if (arr[clickedIndex2] == "") {
    arr.splice(clickedIndex2, 1);
}
log(arr);

// And because you have not clicked on the empty row
// the empty item was never removed. So when you click on 
// another row, a new empty item is added.
const clickedIndex3 = 2;
add(arr, clickedIndex3, '');

// And you have the same result as you have shown us.
log(arr);


function add(array, index, value) {
   array.splice(index, 0, value);
}

function log(arr) {
  // Just for logging horizontally the array.
  console.log(JSON.stringify(arr));
}

А вот как это исправить:

var arr = [1,2,3,4,5,6,7,8,9];

// You click on the second row and one empty item is added.
var clickedIndex1 = 1;
add(arr, clickedIndex1, '');

// You have to keep track of last empty item added 
var lastEmptyIndex = clickedIndex1;

log(arr);


// Now when you clicked on another row, you don't need to 
// check if is empty anymore. You will just remove the stored empty index
var clickedIndex2 = 3;
arr.splice(lastEmptyIndex, 1);

log(arr);

// Now you have your initial array and the new empty will be added 
// at the good position. let's say you have clicked on 4th row
const clickedIndex3 = 3;
add(arr, clickedIndex3, '');
log(arr);


function add(array, index, value) {
   array.splice(index, 0, value);
}

function log(arr) {
  // Just for logging horizontally the array.
  console.log(JSON.stringify(arr));
}

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

var lastEmptyIndex = null; // <----------------- INIT HERE
$(document).on('change','.jenis_mapel', function(event) {
   event.preventDefault();
    if ($(this).val() == "istirahat") //get val of select option (istirahat condition)
    {

        if (lastEmptyIndex) {
          arr.splice(lastEmptyIndex, 1);  // <-------------- Here reset (you can add this if in a function...)
          lastEmptyIndex = null; 
        }

        add(arr,index,'');
        lastEmptyIndex = index; // <------------------ HERE
        var col1;
        var num = 0;

        $('.tb_senin tr').find('td:eq(0)').each(function() { //loop the arr value to first column (jam ke column)
            col1 = $(this).text(arr[num]);
            num++;
        });

        console.log(arr);
    }
    else //(other condition, that the number should be back)
    {
        var tbRow = $('.tb_senin tr').length - 1;

        if (lastEmptyIndex) {
          arr.splice(lastEmptyIndex, 1);  // <-------------- Here
          lastEmptyIndex = null; 
        }

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