- 1
Why is my splice method deleting the wrong array item?
https://code.sololearn.com/W99b5ahx27V5/ Could anyone please tell me how to fix my splice method so that it deletes the right to do item? Thank you! So far it seems to only delete the first item no matter what
2 Réponses
+ 7
@AceDev wrote in his code:
// Added +1 to the prompt code to compensate for the fact that
// arrays are calculated starting index 0.
@Szabo Gabor is right, you need to substract 1 instead add it to compensate the fact than index count start at 0, while position start at 1:
[ 'position1', 'position2', 'position3' ]
index: 0 index: 1 index:2
Anyway, you need to adapt next lines also, because actualy you do another mistake:
function dele (position, amount) {
var amount = 1;
var position =
((parseInt(prompt("What is the number of the item you want to delete?")))-1); // corrected
// this get the value stored at index number position ( so, with correction, at the index entered by user
// anyway, you don't have to redeclare the 'position' variable ( 'var' keyword useless )
var position = todo[position];
todo.splice(position, amount); // that will work only by bypassing previous position
}
So, good code can be the one of @Szabo Gabor for user entering a position number, or this next, for user entering a value to delete:
function dele (position, amount) {
var amount = 1;
var item =
prompt("What is the item you want to delete?");
var position = todo.indexOf(item)
if (item!=-1) todo.splice(position, amount);
else alert("Item not found: todo list unchanged!")
}
+ 4
function dele (position, amount) {
var amount = 1;
var position =
((parseInt(prompt("What is the number of the item you want to delete?")))-1);
todo.splice(position, amount);
}