Friday, November 15, 2019

I learned today about handing in negative numbers to .splice to get stuff off of the end of an array in JavaScript.

var prettyGirl = ['I', 'can', 'swear'];
prettyGirl.push('I', 'can', 'joke');
prettyGirl.push.apply(prettyGirl, ['I', 'say', 'whats', 'on', 'my', 'mind']);
prettyGirl.splice(-3).forEach((word) => {
   alert(word);
});

 
 

Above the -3 behaves like a 9 and we get three alerts containing:

  1. on
  2. my
  3. mind

 
 

Here the -7 acts like a 5.

var prettyGirl = ['I', 'can', 'swear'];
prettyGirl.push('I', 'can', 'joke');
prettyGirl.push.apply(prettyGirl, ['I', 'say', 'whats', 'on', 'my', 'mind']);
prettyGirl.splice(-7, 3).forEach((word) => {
   alert(word);
});

 
 

Giving...

  1. joke
  2. I
  3. say

No comments:

Post a Comment