What is an Array-Like-Object?

  1. the arguments object that is available inside all non-arrow functions.
  2. The jQuery object returned by a jQuery selector like ($(#main)).
  3. The objects that are returned from either document.querySelectorAll() or document.getElementsByClassName().
console:
{
0: 1
1: 2
2: 3
3: 4
4: 5
callee: ƒ functionName()
length: 5
Symbol(Symbol.iterator): ƒ values()
__proto__: Object
}

Definition

  1. At least some of its keys are set to non-negative integers.
  2. It has a length property.

An Array-Like-Object Builder

const arrLikeObjBuilder = (length, func) => {
const arrLikeObj = {};
for(let key = 0; key < length; key++) {
arrLikeObj[key] = func(length, key);
}
arrLikeObj.length = length;
return arrLikeObj;
}
const percents = (length, key) => {  // calculate the percent key is of length, rounded to 1 decimal
let percent = key === 0 ? 0 : Math.round(key / length * 1000) / 10;
return `${key} is ${percent}% of ${length}.`
}
const arrLikeObj = arrLikeObjBuilder(10, percents);
console.dir(arrLikeObj)
console:
{
0: "0 is 0% of 10."
1: "1 is 10% of 10."
2: "2 is 20% of 10."
3: "3 is 30% of 10."
4: "4 is 40% of 10."
5: "5 is 50% of 10."
6: "6 is 60% of 10."
7: "7 is 70% of 10."
8: "8 is 80% of 10."
9: "9 is 90% of 10."
length: 10
__proto__: Object
}
console.log(arrLikeObj[3]); // logs "3 is 30% of 10."
console.log(arrLikeObj.length); // logs 10
console.log(arrLikeObj.join(‘’))
console:
Uncaught TypeError: arrLikeObj.join is not a function”.
console.log(arrLikeObj.hasOwnProperty(7)); // logs true

Array.prototype.[method].call()

Array.prototype.push.call(arrLikeObj, ’10 is 100% of 10.’);
console:
10: "10 is 100% of 10."

Converting an Array Type Object to an Array

Array.prototype.slice.call(arrLikeObj);
Array.from(arrLikeObj);
console:
["0 is 0% of 10.", "1 is 10% of 10.", "2 is 20% of 10.", "3 is 30% of 10.", "4 is 40% of 10.", "5 is 50% of 10.", "6 is 60% of 10.", "7 is 70% of 10.", "8 is 80% of 10.", "9 is 90% of 10.", "10 is 100% of 10."]

Conclusion

const $liByClass = $('.list');
console.dir($liByClass);
console:
{
0: li.list
1: li.list
2: li.list
3: li.list
4: li.list
length: 5
prevObject: w.fn.init [document]
__proto__: Object(0)
}
const liByClass = document.getElementsByClassName('list');
console.dir(liByClass);
console:
{
0: li.list
1: li.list
2: li.list
3: li.list
4: li.list
length: 5
__proto__: HTMLCollection
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Scott Price

Scott Price

7 Followers

Front End Developer with Information Security Experience. See my resume and portfolio at www.scottaprice.com