Zyg*_*tas 228 javascript functional-programming immutable.js
我错过了一个选项如何map使用Listfrom 获取函数内的索引号Immutable.js:
var list2 = list1.map(mapper => { a: mapper.a, b: mapper.index??? }).toList();
文档显示的是map()回报Iterable<number, M>.有什么优雅的方式来满足我的需求吗?
Sam*_*Toh 421
你将能够获得当前迭代index的map通过它的第二个参数的API.
另请参阅: https ://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/map
参数
callback - 生成新数组元素的函数,带有三个参数:
1)currentValue
数组中正在处理的当前元素.2)index
数组中正在处理的当前元素的索引.3)数组
调用了数组映射.
例:
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]
});
Run Code Online (Sandbox Code Playgroud)
输出:
当前迭代为:0
当前元素为:h当前迭代是:1
当前元素是:e当前迭代是:2
当前元素是:l当前迭代是:3
当前元素是:l当前迭代是:4
当前元素是:o
Wil*_*een 19
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);Run Code Online (Sandbox Code Playgroud)
Array.prototype.map():Array.map()是一个对象,它将是this回调函数的值.请记住,您必须使用regular function关键字才能声明回调,因为箭头函数没有自己的this关键字绑定.例如:
const array = [1, 2, 3, 4];
const thisObj = {prop1: 1}
const map = array.map( function (x, index, array) {
console.log(array);
console.log(this)
}, thisObj);Run Code Online (Sandbox Code Playgroud)
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}`);
})Run Code Online (Sandbox Code Playgroud)
> 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
Run Code Online (Sandbox Code Playgroud)