With array-like objects, you can use jQuery.makeArray()
. (Also, with Array.from()
.)
var divs = document.querySelectorAll("div");
var arr = jQuery.makeArray(divs);
function foo() {
return jQuery.makeArray(arguments);
}
foo(1, 'bar', false); // [1, 'bar', false]
It can also nearly work for the 1st object, but it'll need to be given a length
(set to 1 + the greatest, positive, integer property).
var obj = { 0: "a", 1: "b", 2: "c", length: 3 };
var arr = jQuery.makeArray(obj);
If the length
is unknown, you could figure it out first (ref: 9.4.2):
var obj = { 0: "a", 1: "b", 2: "c" };
obj.length = Object.keys(obj).reduce(function (prev, key) {
var index = parseInt(key, 10);
// 9.4.2 Array Exotic Objects
// A String property name P is an array index if and only if...
// ... ToString(ToUint32(P)) is equal to P...
var isInteger = key === String(index);
// ... and ToUint32(P) is not equal to 232−1.
var isUInt32 = index >= 0 && index < Math.pow(2, 32) - 1;
return isInteger && isUInt32 ? index + 1 : prev;
}, 0);
var arr = jQuery.makeArray(obj);
Or, let the engine figure it out, using jQuery.merge()
with an array and the obj
as already suggested.