Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.