8

Array.length-1 returns NaN

 2 years ago
source link: https://www.codesd.com/item/array-length-1-returns-nan.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Array.length-1 returns NaN

advertisements

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)


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);

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK