And*_*ech 23 javascript arrays arguments slice
我遇到了以下代码:
var f = function () {
var args = Array.prototype.slice.call(arguments).splice(1);
// some more code
};
Run Code Online (Sandbox Code Playgroud)
基本上,结果args是一个数组,它是arguments没有第一个元素的副本.
但我不明白究竟是为什么f的arguments(其是保持该函数的输入参数成阵列状的对象的对象)对象被传递到slice方法,以及如何slice(1)被移除第一元件(定位在索引0) .
有人可以帮我解释一下吗?
PS代码来自此部分应用程序功能
Cre*_*esh 40
<注意>
该链接答案的实际代码是:
var args = Array.prototype.slice.call(arguments, 1);
Run Code Online (Sandbox Code Playgroud)
即"切片",而非"拼接"
</ Note>
首先,该slice方法通常用于制作调用它的数组的副本:
var a = ['a', 'b', 'c'];
var b = a.slice(); // b is now a copy of a
var c = a.slice(1); // c is now ['b', 'c']
Run Code Online (Sandbox Code Playgroud)
所以简短的回答是代码基本上是模拟的:
arguments.slice(1); // discard 1st argument, gimme the rest
Run Code Online (Sandbox Code Playgroud)
但是你不能直接这样做.的特殊arguments对象(可用的所有JavaScript函数的执行上下文内),尽管阵列- 喜欢的,因为它通过支持索引[]用数字键操作,实际上不是阵列; 你不能把.push它,.pop它,或.slice它,等等.
该代码实现这一点的方式是通过"欺骗"的slice功能(这又是不可用的上arguments对象)运行在的上下文中 arguments,通过Function.prototype.call:
Array.prototype.slice // get a reference to the slice method
// available on all Arrays, then...
.call( // call it, ...
arguments, // making "this" point to arguments inside slice, and...
1 // pass 1 to slice as the first argument
)
Run Code Online (Sandbox Code Playgroud)
Array.prototype.slice.call(arguments).splice(1)完成同样的事情,但做了一个无关的调用splice(1),它从从index开始返回的数组中删除元素并继续到数组的末尾.在IE中不起作用(它在技术上缺少第二个参数,告诉它删除IE和ECMAScript要求的项目数).Array.prototype.slice.call(arguments)1splice(1)
| 归档时间: |
|
| 查看次数: |
17431 次 |
| 最近记录: |