我缺少如何map
使用List
from获取函数内部索引号的选项Immutable.js
:
var list2 = list1.map(mapper => { a: mapper.a, b: mapper.index??? }).toList();
文档显示的是map()
回报Iterable<number, M>
。有什么优雅的方式可以满足我的需求吗?
我缺少如何map
使用List
from获取函数内部索引号的选项Immutable.js
:
var list2 = list1.map(mapper => { a: mapper.a, b: mapper.index??? }).toList();
文档显示的是map()
回报Iterable<number, M>
。有什么优雅的方式可以满足我的需求吗?
您将能够通过其第二个参数index
获取该map
方法的当前迭代。
例子:
const list = [ 'h', 'e', 'l', 'l', 'o'];
list.map((currElement, index) => {
console.log("The current iteration is: " + index);
console.log("The current element is: " + currElement);
console.log("\n");
return currElement; //equivalent to list[index]
});
输出:
The current iteration is: 0 <br>The current element is: h
The current iteration is: 1 <br>The current element is: e
The current iteration is: 2 <br>The current element is: l
The current iteration is: 3 <br>The current element is: l
The current iteration is: 4 <br>The current element is: o
另见: https : //developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/map
参数
callback - 生成新数组元素的函数,采用三个参数:
1) currentValue
数组中正在处理的当前元素。2) index
当前正在处理的元素在数组中的索引。3) array
调用了数组映射。
Array.prototype.map()
指数:可以Array.prototype.map()
通过回调函数的第二个参数访问索引。下面是一个例子:
const array = [1, 2, 3, 4];
const map = array.map((x, index) => {
console.log(index);
return x + index;
});
console.log(map);
Array.prototype.map()
:Array.map()
是一个对象,它将作为this
回调函数的值。请记住,您必须使用常规function
关键字来声明回调,因为箭头函数没有自己的this
关键字绑定。例如:
const array = [1, 2, 3, 4];
const thisObj = { prop1: 1 }
const map = array.map((x, index, array) => {
console.log(array);
console.log(this)
}, thisObj);
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
arr.map((myArr, index) => {
console.log(`your index is -> ${index} AND value is ${myArr}`);
})
> output will be
index is -> 0 AND value is 1
index is -> 1 AND value is 2
index is -> 2 AND value is 3
index is -> 3 AND value is 4
index is -> 4 AND value is 5
index is -> 5 AND value is 6
index is -> 6 AND value is 7
index is -> 7 AND value is 8
index is -> 8 AND value is 9
使用lambda:
import {addIndex, map} from 'ramda';
const list = [ 'h', 'e', 'l', 'l', 'o'];
const mapIndexed = addIndex(map);
mapIndexed((currElement, index) => {
console.log("The current iteration is: " + index);
console.log("The current element is: " + currElement);
console.log("\n");
return 'X';
}, list);