在js的学习中,经常看到Array.prototype.slice.call(arguments)
这样就可以得到一个函数中参数的数组。
那么怎么将一个 {}对象转换为数组呢。下面做了一些自己的代码测试
b = {
length: 3,
2: 1,
1: 2,
c: 3
}
var a = {
length: 2,
0: 'first',
1: 'second'
};
console.log(Array.prototype.slice.call(a));
console.log(Array.prototype.slice.call(b));
得到结论:
采用这种方式的对象转数组需要满足以下条件:
1、对象中要有length属性。
2、要以number为对象的key值
注意:这个方式会根据length的长度创建一个数组。然后根据key值为索引创建数组。如果索引超出数组。则无效