我写了一个函数,该函数对Objects的每个实例都适用(数组就是这些实例)。
Object.prototype.toArray = function()
{
if(!this)
{
return null;
}
var c = [];
for (var key in this)
{
if ( ( this instanceof Array && this.constructor === Array && key === 'length' ) || !this.hasOwnProperty(key) )
{
continue;
}
c.push(this[key]);
}
return c;
};
用法:
var a = [ 1, 2, 3 ];
a[11] = 4;
a["js"] = 5;
console.log(a.toArray());
var b = { one: 1, two: 2, three: 3, f: function() { return 4; }, five: 5 };
b[7] = 7;
console.log(b.toArray());
输出:
> [ 1, 2, 3, 4, 5 ]
> [ 7, 1, 2, 3, function () { return 4; }, 5 ]
它对任何人都可能有用。