Array.prototype.slice奇怪的行为

Der*_*ang 8 javascript

考虑这段代码,每行末尾有控制台输出:

function whatever() {
  console.log(arguments) // { '0': 1, '1': 2, '2': 3, '3': 4, '4': 5 }
  console.log(Array.prototype.slice.call(arguments)) // [ 1, 2, 3, 4, 5 ]
  console.log(Array.prototype.slice.call({ '0': 1, '1': 2, '2': 3, '3': 4, '4': 5 })) // []
}

whatever(1,2,3,4,5)
Run Code Online (Sandbox Code Playgroud)

为什么第三个console.log输出一个空数组呢?

bas*_*kum 13

因为为了Array.prototype.slice工作,你需要传递一个类似数组的对象.并且为了使对象适合该类别,它需要一个length您的对象没有的属性.试试这个:

var arr = { '0': 1, '1': 2, '2': 3, '3': 4, '4': 5 };
arr.length = 5;
var res = Array.prototype.slice.call(arr);
console.log(res);
Run Code Online (Sandbox Code Playgroud)

小提琴