removing of array elements an issue
I have a situation where i add tables on a click of button and each table is stored in arr开发者_如何学编程ay. Now when i remove 2 or 3 tables, wrong index are being removed.
addTable: function (obj) {
for (var i = 0; i < obj.length; i++) {
// Adding of table
array.push(obj)
// delete code of the table
(function (i) {
deleteButton.addEventListener('click', function (e) {
array.splice(i, 1);
});
})(i);
}
}
The problem i am facing is the value of i is always zero
. each time i click on the button a the addTable
function is called and the counter is always zero
and that is passed to the function(i)
too.
Any ideas on how can keep track of different i or counter so that it deletes the correct index in the array
Here is an update
this is the sample object i am sending each time.
Each time i click on the Add Table button, the same object is being passed. Now i am having difficulty in keeping track of the index of each item.
Once you've removed one table, all other tables have moved and their indexes that you installed in the delete Buttons will be wrong now. When you remove items from the array, all indexes shift.
So, suppose you remove table 3. Then, you press delete for table 4. It's got an index of 4, but since you already removed table 3, it's in spot 3 in the array now (after the previous delete), not spot 4. But, you're code still has i==4 associated with that table and is trying to delete it here, but it's not there any more.
What you are doing is just not a good way to do this. If you want to expand further on what you're really trying to do, we can help with much better solutions.
Given the limited info we have so far, all I know of to do is to find the item in the array (wherever it might have moved to) and delete it from there.
addTable: function (obj) {
for (var i = 0; i < obj.length; i++) {
// Adding of table
array.push(obj)
// delete code of the table
(function (item) {
deleteButton.addEventListener('click', function (e) {
// search through the array to find where this item is
// and remove it from the array
for (var j = 0; j < array.length; j++) {
if (array[j] === item) {
array.splice(j, 1); // remove it
break;
}
}
});
})(obj);
}
}
I do not know about deleteButton
, but in case that obj
is array with only one element (length
equals 1): [{....}]
and array.push
is native Array.prototype.push
method then:
addTable: function (obj) {
// Adding of table
var index=array.push(obj);
// delete code of the table
deleteButton.addEventListener('click', function (e) { array.splice(index, 1); });
}
if obj.length
is undefined i
will allways be 0
further more, then i < obj.length
return false
and the for
loop will never execute
if obj
passed in is this object:
var addObjectResponse = [{...}];
then addObjectResponse
is an array of 1, hence i
will allways be 0
i = 0
obj.length = 1
i < obj.length
=> 0 < 1
=> true once
精彩评论