简体   繁体   English

在javascript映射es6中传递其他参数

[英]Passing Additional Arguments in javascript map es6

I'm trying to pass in an additional parameter to the callback function in a map. 我正在尝试将其他参数传递给地图中的回调函数。 The value is not passed when I use es6 syntax for callback function and in map. 当我将es6语法用于回调函数和在map中时,不会传递该值。

Here is the es6 map and callback function 这是es6映射和回调函数

 const convertEvents = action.payload.map(item => convertEvent(item), { role: 'teacher' }); const convertEvent = (item) => { console.log('----------convertEvent role----------'); console.log(this.role); return item; }; 

But when I used old javascript syntax the value is passed and the code works correctly 但是,当我使用旧的javascript语法时,会传递值并且代码可以正常工作

 const convertEvents = action.payload.map(convertEventRole, { role: 'teacher' }); function convertEventRole(item) { console.log('----------convertEvent role----------'); console.log(this.role); return item; } 

Can you tell me why the es6 code didn't work? 您能告诉我为什么es6代码不起作用吗?

The 2nd parameter passed to Array.map() is the thisArg , which is: 传递给Array.map()的第二个参数是thisArg ,它是:

Value to use as this when executing callback.

With a standard JS function , this is defined by execution context, but you can change it using Function.bind() , and other methods. 使用标准的JS functionthis是由执行上下文定义的,但是您可以使用Function.bind()和其他方法进行更改。

An arrow function this is defined by the context in which it's declared, and thus cannot be changed. 箭头功能this是通过在其中它被声明,并且因此不能被改变的上下文中定义。 That's why you can use the assigned thisArg with an arrow function. 这就是为什么您可以将分配的thisArg与箭头功能一起使用的原因。

You can approximate the functionality using partial application and IIFE : 您可以使用部分应用程序IIFE来估算功能

 const arr = [1, 2, 3]; const result = arr.map(((m) => (n) => n + m)(5)); console.log(result); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM