Last active
March 6, 2025 07:56
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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