Mic*_* SM 4 javascript node.js
1)我有以下代码:
Run Code Online (Sandbox Code Playgroud)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
Run Code Online (Sandbox Code Playgroud)
2)如果我将callIt更改为:
Run Code Online (Sandbox Code Playgroud)var callIt = function(fn) { return fn.apply(this, Array.prototype.slice.apply(arguments)); };
Nodejs没有抱怨,但结果不是预期的,传递了额外的第一个参数.
3)如果我将callIt更改为:
Run Code Online (Sandbox Code Playgroud)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开发者工具控制台中运行测试,如下所示:
Run Code Online (Sandbox Code Playgroud)> 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) []
现在切片不适用于类似数组的对象.
我对此感到困惑.请解释.
我引用了以下内容: Array_generic_methods
你的问题是apply函数方法需要一个数组作为它的第二个参数 - 你传递的是TypeError来自的地方1.相反,使用[1]或更好的call方法:
fn.apply(this, Array.prototype.slice.call(arguments, 1));
Run Code Online (Sandbox Code Playgroud)
为什么它不工作的原因{0:"a", 1:"asdf"}是,这是不是一个类似数组的对象-它没有length产权.[].slice.call({0:"a", 1:"asdf", length:2}, 0)会做的.
| 归档时间: |
|
| 查看次数: |
2321 次 |
| 最近记录: |