In JavaScript array-like objects are objects that have a length
property and indexed elements. Therefore, you can check whether an object is array-like or not in the following way:
function isArrayLike(item) { return ( item instanceof Object && typeof item.length === 'number' && item.length >= 0 ); }
For example, this would return true
for the following:
console.log(isArrayLike([])); // true console.log(isArrayLike([1, 2, 3])); // true console.log(isArrayLike(['foo', 'bar', 'baz'])); // true
console.log(isArrayLike(new String('abc'))); // true
console.log(isArrayLike({ length: 0 })); // true console.log(isArrayLike({ 0: 'foo', length: 1 })); // true console.log(isArrayLike({ 0: 'foo', 4: 'bar', length: 5 })); // true console.log(isArrayLike({ 4: 'bar', 0: 'foo', length: 5 })); // true
It returns false
for the following:
console.log(isArrayLike({})); // false (does not have length) console.log(isArrayLike({ 0: 'foo' })); // false (does not have length) console.log(isArrayLike({ 0: 'foo', length: 'abc' })); // false (has non-numeric length)
console.log(isArrayLike(null)); // false (is a primitive) console.log(isArrayLike(undefined)); // false (is a primitive)
console.log(isArrayLike(123)); // false (is a primitive) console.log(isArrayLike(Number(123))); // false (does not have length) console.log(isArrayLike(new Number('123'))); // false (does not have length) console.log(isArrayLike(BigInt(123))); // false (does not have length)
console.log(isArrayLike(Boolean(true))); // false (does not have length) console.log(isArrayLike(new Boolean(true))); // false (does not have length)
console.log(isArrayLike('foo')); // false (is a primitive) console.log(isArrayLike(String('foo'))); // false (is a primitive) console.log(isArrayLike(Symbol('foo'))); // false (is a primitive)
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.