gpt4 book ai didi

javascript - Array.prototype.slice.appy(arguments, 1) 的问题

转载 作者:搜寻专家 更新时间:2023-10-31 23:10:07 26 4
gpt4 key购买 nike

1) 我有以下代码:

var callIt = function(fn) {
return fn.apply(this, Array.prototype.slice.apply(arguments, 1));
};

在nodejs中调用callIt时报错:

    return fn.apply(this, Array.prototype.slice.apply(arguments, 1));
^
TypeError: Function.prototype.apply: Arguments list has wrong type

2) 如果我将 callIt 更改为:

var callIt = function(fn) {
return fn.apply(this, Array.prototype.slice.apply(arguments));
};

Nodejs 没有报错,但是结果不是预期的,多了第一个参数传入。

3) 如果我将 callIt 更改为:

var callIt = function(fn) {
var args = Array.prototype.slice.apply(arguments);
return Function.prototype.apply(fn, args.slice(1));
//return fn.apply(this, args.slice(1)); //same as above

};

它按预期工作。

4) 如果我像这样在 Chrome 开发者工具控制台中运行测试:

> var o={0:"a", 1:"asdf"}
undefined
> o
Object
0: "a"
1: "asdf"
__proto__: Object
> Array.prototype.slice.call(o,1)
[]
> Array.prototype.slice.call(o)
[]

现在 slice 不适用于类似数组的对象。

我对这些感到困惑。请解释。

我引用了以下内容: Array_generic_methods

最佳答案

你的问题是 apply method of functions期望一个数组作为它的第二个参数——这就是你的 TypeError 的来源,你传递了 1。相反,使用 [1] 或更好的 call method :

fn.apply(this, Array.prototype.slice.call(arguments, 1));

它在 {0:"a", 1:"asdf"} 上不起作用的原因是它不是类数组对象 -它没有 length 属性。 [].slice.call({0:"a", 1:"asdf", length:2}, 0) 会做到这一点。

关于javascript - Array.prototype.slice.appy(arguments, 1) 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14870695/

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