原理解释:
Array.prototype.slice.call()
方法能够将一个具有length
属性的对象转换为数组。比如我自己定义一个具有length属性的对象:
var obj = { 0: 'one', 1: 'two', 2: 'three', length: 3};
console.log(Array.prototype.slice.call(obj)); // ["one", "two", "three"]
function foo(a,b,c,d) { var arg = Array.prototype.slice.call(arguments); console.log(arg); // ["a", "b", "c", "d"]console.log(typeof arguments); // objectconsole.log(arguments); //Arguments(4) ["a", "b", "c", "d", callee: ?, Symbol(Symbol.iterator): ?]
}
foo("a","b","c","d");
Array.prototype.slice.call(arguments)
的作用是将函数传入的参数转换为数组对象。那大家肯定有疑问,为什么不直接使用arguments
对象呢?这里需要注意的是typeof arguments
打印出的是object
,可以看出arguments
并不是真正的数组,它是一个对象。
ES6方法转为数组:
(1)、Array.from()
Array.from
方法用于将两类对象转为真正的数组:类似数组的对象(array-like object)
和可遍历(iterable)
的对象(包括 es6
新增的数据结构Set
和 Map
)。
let demo = new Set(['a', 'b', 'c']);
Array.from(demo); // ['a', 'b', 'c'];
(2)、扩展运算符...
function foo(a,b,c,d) {console.log([...arguments]); // ["a", "b", "c", "d"]
}
foo("a","b","c","d");