simplexshotz
simplexshotz

Reputation: 309

array.length-1 returns NaN

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

Answers (2)

Ori Drori
Ori Drori

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

eqwert
eqwert

Reputation: 507

As Volem said, you are missing the second parameter of splice (docs).

You can also just use pop if you are only removing one element from the end of the array (docs)

Upvotes: 0

Related Questions