Javascript ES5数组函数.每秒钟&“此值&"争论 [英] Javascript ES5 Array functions. forEach second "This Value" argument

查看:40
本文介绍了Javascript ES5数组函数.每秒钟&“此值&"争论的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java语言的新手.而且我遇到了以下问题.

I'm newbie in Javascript. And I faced the following question.

此处所述,几乎所有ES5数组函数(forEach,map,filter,每个)都可以使用其他第二个参数.

As stated here, almost all ES5 Array functions (forEach, map, filter, every, some) can take additional second argument.

如果指定了该函数,则将其作为第二个参数的方法来调用.也就是说,您传递的第二个参数将成为您传递的函数内部的 this 关键字的值.

array.forEach(function(currentValue, index, arr), thisValue)
array.map(function(currentValue, index, arr), thisValue)

相反:

array.reduce(callback, [initialValue])
array.reduceRight(callback, [initialValue])

请注意,reduce()和reduceRight()都不接受可选参数,该参数指定要在其上调用缩减函数的this值.如果需要将还原功能作为特定对象的方法调用,请参见 Function.bind()方法.

Note that neither reduce() nor reduceRight() accepts an optional argument that specifies the this value on which the reduction function is to be invoked. See the Function.bind() method if you need your reduction function invoked as a method of a particular object.

这是什么意思:作为特定对象的方法被调用"?任何人都可以提供一些示例,它如何影响我的代码?

What does it mean: "to be invoked as a method of a particular object"? Could anyone provide some example how it may affect on my code?

谢谢.

推荐答案

很简单.在回调函数中, this 值将是传递给数组方法的第二个参数.如果您不使用 this ,则该参数无关紧要,则不需要传递它.

It's simple. In the callback function, the this value will be the second argument passed to the array method. If you won't use this, then the argument is irrelevant and you don't need to pass it.

"use strict";
[0].forEach(function(currentValue, index, arr) {
  console.log(this); // 1234
}, 1234);

请注意,在草率模式下, this 值将转换为对象.因此,如果省略参数或使用 undefined ,则将获取全局对象.

Note that in sloppy mode, the this value is converted to an object. So if you omit the argument or use undefined, you will get the global object instead.

如果您需要与 reduce 类似的东西,请使用 bind :

If you need something similar with reduce, then use bind:

"use strict";
[0, 1].reduce(function(prevValue, currValue, index, arr) {
  console.log(this); // 1234
}.bind(1234));

这篇关于Javascript ES5数组函数.每秒钟&“此值&"争论的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆