0

有人告诉我,这对于使“参数”对象成为真正的数组以及创建现有数组的副本很有用。但是,是否有必要转换为类似数组的对象?这样做有什么好处?

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,是因为它们的键不是数字吗?

4

1 回答 1

0

如果你做了:

x={1:1,2:1,0:55,length:3};
toArray(x);

// result [55, 1, 1]

数组将期望键是数字。所以它通过查看 0... undefined 查看 1... undefined 查看 2... '2'

所以是的,这是因为他们的键不是数字的。

希望这可以帮助

于 2013-07-25T18:50:36.547 回答