Javascript Javascript 每日测试 - 第十期 6

请问以下代码的弹出值?

function testFunction() {
    var args = Array.prototype.slice.call(arguments, 1, 2);
    alert(args);
}

testFunction(1,2,3);

本道题的目的是为了温习三个知识:

  1. arguments 是一个类数组,但不是一个数组
  2. 使用Array.prototype.slice 可以将 arguments 转换为一个数组
  3. slice 方法接受两个参数 start 和 end

使用 Array.prototype.slice 将 arguments 转换为数组可看作是个 hack。我们可以去追根溯源,了解些前因后果。

ECMAScript 规范 94 页对 Array.prototype.slice 有一个备注

The slice function is intentionally generic; it
does not require that its this value be an Array
object.

Therefore it can be transferred to other kinds of
objects for use as a method. Whether the slice

function can be applied successfully to a host object
is implementation-dependent.

Generic 可以理解为 Java 里的泛型。对数组来说,就是在 JavaScript, 只要一个对象有 length 属性且可用下标的方式取得所包含的元素,那么它就是 Generic 。

所以使用 Array.prototype.slice.call(arguments) 可以得到一个数组, 除 slice 外, 根据测试使用数组的 splice 方法也可以实现类似的效果

Array.prototype.splice.call(arguments, 0, arguments.length)

同时,使用 Array.prototype.slice 时要注意, 第一个参数是 start,第二个参数是 end。 第二个参数可以不指定,那么表示取出全部。但不能为 null 或 undefined,否则将得到一个空数组(详细)。

这里是《Javascript 每日测试 - 第十期》的 永久连接(Permalink),欢迎您 留言 或发送 Trackback。您也可以查看此篇文章的 Wap 版本(适用于移动设备)。 最后,如果您对本站的内容感兴趣,欢迎您 订阅本站
欢迎您留言

请输入您的称呼

请输入您的电子邮件

请您输入留言内容