Array.prototype.map路过Function.prototype.call产生作为参数的函数时,不是一个函数 [英] Array.prototype.map is not a function when passing a function generated by Function.prototype.call as argument
问题描述
有时我用Array.prototype.map梅索德像这样:
变种数组= ['1','2','3','4']图(parseFloat)。 //结果为[1,2,3,4]
parseInt函数需要两个参数就在这种情况下返回不正确的值
块引用>现在我想要做的是不是这个code:
VAR阵列= ['一','B','C','D'。图(函数(项目){
返回item.toUpperCase();
}); //结果为['A',B','C','D']我试过这样:
VAR阵列= ['一','B','C','D']地图(''toUpperCase.call)。
有人可以解释我为什么我得到一个错误,指出:
未捕获的类型错误:[一,B,C,D]图不是一个函数
块引用>解决方案第一个问题是你传递函数
''。toUpperCase.apply
其中是同样为Function.prototype.apply的
:它不绑定会发生什么事,相当于
['一','B','C','D'。图(函数(V,I,编曲){
返回undefined.apply(V,I,ARR)
});如果您在使用绑定
['一','B','C','D']地图(''toUpperCase.apply.bind(''与toUpperCase)。)。
那么你有第二个问题:
地图
不只有一个参数传递给回调函数。它还通过指数和整个阵列。您可以修复两个问题。
['一','B','C','D']地图(函数(五){return'指令'.toUpperCase.apply(V)})。
(超过一个固定的解释,吧)
使用
呼叫
更容易和可以是固定的:VAR ARR = ['一','B','C','D'。图(''。toUpperCase.call.bind(''。与toUpperCase)) ;
应被写为
VAR ARR = ['一','B','C','D']地图(Function.prototype.call.bind(''与toUpperCase)。)。
边注:你很幸运在第一个例子中使用
parseFloat
。与parseInt函数
尝试。Sometimes I use the Array.prototype.map methode like so :
var array = ['1', '2', '3', '4'].map(parseFloat); // the result is [1, 2, 3, 4]
parseInt takes 2 arguments it returns incorrect values in this case
Now what I'm trying to do is instead of this code :
var array = ['a', 'b', 'c', 'd'].map( function (item) { return item.toUpperCase(); }); // the result is ['A', B', 'C', 'D']
I tried this :
var array = ['a', 'b', 'c', 'd'].map(''.toUpperCase.call);
can someone explain to me why I get an error that says :
Uncaught TypeError: ["a","b","c","d"].map is not a function
解决方案The first problem is you pass the function
''.toUpperCase.apply
which is the same asFunction.prototype.apply
: it isn't bound.What happens is equivalent to
['a', 'b', 'c', 'd'].map(function(v, i, arr){ return undefined.apply(v, i, arr) });
If you bind it using
['a', 'b', 'c', 'd'].map(''.toUpperCase.apply.bind(''.toUpperCase));
then you have a second problem:
map
doesn't pass only one parameter to your callback. It also pass the index and the whole array.You could "fix" the two problems with
['a', 'b', 'c', 'd'].map(function(v){ return ''.toUpperCase.apply(v) });
(more an explanation than a fix, right)
Using
call
is easier and can be fixed:var arr = ['a', 'b', 'c', 'd'].map(''.toUpperCase.call.bind(''.toUpperCase));
which should be written as
var arr = ['a', 'b', 'c', 'd'].map(Function.prototype.call.bind(''.toUpperCase));
Side note: you were lucky to use
parseFloat
in the first example. Try withparseInt
.这篇关于Array.prototype.map路过Function.prototype.call产生作为参数的函数时,不是一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!