JSFiddle - React, Tailwind, and code Playground
by jfriend00
HTML
<script src="http://files.the-friend-family.com/log.js"></script>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
JavaScript
var testItems = [
document.querySelectorAll(".test"),
[1,2,undefined],
[undefined, undefined, undefined],
{"0": "aa", "1": "bb", "length": 2},
{"0": "aa", "1": undefined, "length": 2},
{"0": "aa", "1": undefined, "length": 0},
document.body.children,
document.getElementsByClassName("test"),
new Uint8Array(10),
new String("foo"),
"----------",
// the ones after here are supposed to return false
{"0": "aa", "1": "bb", "length": "2"},
{"0": "aa", "1": "bb", "length": 3},
{"0": "aa", "1": "bb", "length": "hello"},
document,
function() {},
null,
1,
"foo",
undefined
];
function isArrayLike(item) {
return (
Array.isArray(item) ||
(!!item &&
typeof item === "object" &&
typeof (item.length) === "number" &&
(item.length === 0 ||
(item.length > 0 &&
(item.length - 1) in item)
)
)
);
}
(function() {
log(isArrayLike(arguments));
})(1, 2, 3);
for (var i = 0; i < testItems.length; i++) {
if (testItems[i] === "----------") {
log("<hr>");
} else {
log(isArrayLike(testItems[i]));
}
}
log("<hr>");
log("done");