有人告诉我,这对于使“参数”对象成为真正的数组以及创建现有数组的副本很有用。但是,是否有必要转换为类似数组的对象?这样做有什么好处?
function toArray(obj) {
return Array.prototype.slice.call(obj);
}
function bind(scope, fn) {
return function() {
// why not just return fn.apply(scope, arguments); ?
return fn.apply(scope, toArray(arguments));
};
}
我知道'arguments'对象的好处是它包含'length'属性,所以我们可以转换为类似数组的对象,但是当我通过传入一个对象来测试它时
x = {
'a': 'a',
'tt': 'tt',
'2':'2',
length:3
};
toArray(x); // [undefined x 2, 2]
它返回一个包含元素的数组undefined
,是因为它们的键不是数字吗?