Skip to content

Instantly share code, notes, and snippets.

@paceaux
Last active December 9, 2019 20:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paceaux/770d5d0ce32399117de8a7ccad02131d to your computer and use it in GitHub Desktop.
Save paceaux/770d5d0ce32399117de8a7ccad02131d to your computer and use it in GitHub Desktop.
Samples of loops over an array that seem to show an implicit and explicit undefined for arrays
function ifIn(array) {
console.group(`ifIn======`);
let i = 0;
while (i < array.length) {
if (i++ in array) {
console.log(`${i - 1} is in the array`);
}
}
console.groupEnd();
}
function forIn(array) {
console.group(`forIn======`);
let i = 0;
for (item in array) {
console.log(array[item], `index = ${i++}`);
}
console.groupEnd();
}
function forOf(array) {
console.group(`forOf======`);
let i = 0;
for (item of array) {
console.log(item, `index = ${i++}`);
}
console.groupEnd();
}
function forEach(array) {
console.group(`forEach======`);
let i = 0;
array.forEach(item => console.log(item, `index = ${i++}`));
console.groupEnd();
}
function mapIt(array) {
console.group(`map======${array}`);
let i = 0;
const newArr = array.map(item => { console.log(item, `index = ${i++}`); return item;})
console.groupEnd();
}
function testArray(array, label) {
console.group(label, array)
ifIn(array);
forIn(array);
forOf(array)
forEach(array);
mapIt(array);
console.groupEnd();
}
console.clear();
const slotted = [,,'slotted one'];
const explicit = [undefined, undefined, 'explicit one'];
const gapped = [];
gapped[2] = 'gapped one';
const presized = new Array(3);
presized[2] = 'presized one';
testArray(slotted, `const slotted = [,,'slotted one'];`);
testArray(explicit, `const explicit = [undefined, undefined, 'explicit one'];`);
testArray(gapped, `const gapped = [];
c[2] = 'gapped one';`);
testArray(presized, `const presized = new Array(3);`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment