Reputation: 309
I'm trying to remove the last item from an array, but it's not working. I did some debugging and found that array.length-1 was returning NaN for some reason. Oddly enough, array.length (without the -1) worked just fine.
lettersA.splice(lettersA.length-1);
Any answers? (I'm using p5 in case that helps at all)
Upvotes: 0
Views: 2320
Reputation: 191976
Using Array#splice in this way actually works because the start
parameter is the last item, and since you've omitted the deleteCount
parameter it will remove everything from start
to the end of the array - the last item.
I think that the NaN you describe is cause by the return value of Array#slice. Slice returns an array that contains the deleted element(s), and you're probably trying to use this array as a number.
Example:
var lettersA = ['angel', 'clown', 'mandarin', 'sturgeon'];
console.log("removed element: ", lettersA.splice(lettersA.length-1));
console.log("Array: ", lettersA);
If you want to get the removed value use Array#pop. Array#pop returns the removed element, without wrapping it in an array.
Example:
var lettersA = ['angel', 'clown', 'mandarin', 'sturgeon'];
console.log("Removed element :", lettersA.pop());
console.log("Array: ", lettersA);
Upvotes: 1