Skip to content

Instantly share code, notes, and snippets.

@pulges
Last active August 29, 2015 13:56
Show Gist options
  • Save pulges/9345335 to your computer and use it in GitHub Desktop.
Save pulges/9345335 to your computer and use it in GitHub Desktop.
Javascript tricks for traversing arrays
// toggle between two list values
var i = 1,
toggleList = ['one', 'two'];
console.log(toggleList[i ^= 1]); // one
console.log(toggleList[i ^= 1]); // two
console.log(toggleList[i ^= 1]); // one
// toggle through longer array
// limitation: list values should not be falsy ("", null, 0)
var j = -1,
list = ['one', 'two', 'three'];
console.log(list[j = (list[++j]) ? j : 0]); // one
console.log(list[j = (list[++j]) ? j : 0]); // two
console.log(list[j = (list[++j]) ? j : 0]);// three
console.log(list[j = (list[++j]) ? j : 0]); // one
// iterate through array once
// limitation: list values should not be falsy ("", null, 0)
// works cause ++ is executed after returning the variable
var k = 0,
list = ['one', 'two', 'three'],
val;
while (val = list[k++]) {
console.log(val); // one, two, three
}
// reverse iterate through array
var list = ['one', 'two', 'three'],
i = list.length;
while (i--) {
console.log(list[i]); // three, two, one
}
// init array with zeros
// array map needs polyfill for ie8 (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)
var arr = Array.apply(null, new Array(10)).map(function () {return 0;});
console.log(arr); //[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment