gpt4 book ai didi

javascript - 关于 JavaScript 的 slice 和 splice 方法的问题

转载 作者:行者123 更新时间:2023-12-02 22:32:45 26 4
gpt4 key购买 nike

我遇到了以下代码:

var f = function () {
var args = Array.prototype.slice.call(arguments).splice(1);

// some more code
};

基本上,args 中的结果是一个数组,它是没有第一个元素的 arguments 的副本。

但我无法确切理解的是为什么 farguments (这是一个将函数的输入参数保存到类似数组的对象中的对象)对象被传递给 slice 方法,以及 slice(1) 如何删除第一个元素(位于索引 0 处)。

谁能帮我解释一下吗?

P.S.代码来自这个partial application function

最佳答案

<注意>
实际代码来自 linked answer是:

var args = Array.prototype.slice.call(arguments, 1);

即“切片”,而不是“拼接”

首先,slice方法常用于make a copy of the array it's called on :

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']

所以简短的答案是代码基本上是在模拟:

arguments.slice(1); // discard 1st argument, gimme the rest

但是你不能直接这样做。 special arguments object (在所有 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
)

Array.prototype.slice.call(arguments).splice(1)完成同样的事情,但对 splice(1) 进行了额外的调用,它从 Array.prototype.slice.call(arguments) 返回的数组中删除元素从索引 1 开始并继续到数组的末尾。 splice(1)在 IE 中不起作用(从技术上讲,它缺少第二个参数,告诉它需要删除 IE 和 ECMAScript 需要多少个项目)。

关于javascript - 关于 JavaScript 的 slice 和 splice 方法的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1777705/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com