Blog

Splice doesn't work very well in a JavaScript for loop

That is all. Be careful.

var numbers = [1,2,3,4,5,6,7,8,9,10];
for(var i=0; i<numbers.length; i++){
  if(numbers[i] - 5 < 0){
    numbers.splice(i,1);
  }
}

console.log(numbers);
//Logs: [2, 4, 5, 6, 7, 8, 9, 10]

The problem is, when you splice inside a for loop, you're ruining the index that you're using to reference the other elements in the array. There are some really smart ways to get around this using jquery's $.grep function, but there's also a simpler way, assuming you don't need to do anything in an upward order - you can just reverse the for loop, using -- rather than ++.

Like so:

var numbers = [1,2,3,4,5,6,7,8,9,10];
for(i=numbers.length-1; i>=0;i--){
  if(numbers[i] - 5 < 0){
    numbers.splice(i,1);
  }
}

console.log(numbers);
//Logs: [5, 6, 7, 8, 9, 10] 

Because you start at the top, none of the values get upset when you start permanently deleting and shifting values across. Enjoy!


Ends:

New icons!

So, I've been working on some new elements for the site, to go... somewhere! I'm following along with the flat UI style that seems so ever popular these days. Check out these SVGs I just blasted out!

They are supposed to represent:

Spirograph Generator

Here is something I cobbled together with a bit of maths I tried desperately to remember from school. There are some pretty intense possible calculations, I think I definitely crashed codepen at one point (nothing worked in my pen, the latest pens feed didn't work, and - mysteriously - hours later the pen had been edited with some JavaScript commented out...

Anyway, here it is, its looking pretty strong I think! There are a few tweaks to be made, for example there are 'repeatable' patterns where as some numbers change, it just draws over itself rather than trace a new evolution.

The dream is to add animation, but to be honest... I think that step was what destroyed codepen, and my brain!

See the Pen Spirograph generator by djave_co (@sheepysheep60) on CodePen

New CSS update!

I updated my site's main CSS file. I say 'updated', I really should say 'culled' as most of what was lurking in the multiple stylesheets was just waffle, built up over years of gradual updates.

I hope you like it, every page has a random primary colour, but other than that is super stripped down. I use a few grids I made in gridpak, and some colours from flatuicolours, and some new fonts: Montserrat, Roboto Slab and Source code pro for the code snippets.

Feedback welcome, and encouraged!

I also stripped down and updated the ridiculous rules of Carl Cox, one of the best and most ridiculous drinking games ever conceived.