Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/428.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 函数的内部索引_Javascript_Functional Programming_Immutable.js - Fatal编程技术网

Javascript 函数的内部索引

Javascript 函数的内部索引,javascript,functional-programming,immutable.js,Javascript,Functional Programming,Immutable.js,我缺少一个选项,如何使用List从Immutable.js获取映射函数中的索引号: var list2=list1.map(mapper=>{a:mapper.a,b:mapper.index???}).toList(); 该map()返回Iterable。有什么优雅的方法可以满足我的需要吗?您可以通过第二个参数获得map方法当前迭代的索引 示例: The current iteration is: 0 <br>The current element is: h The curr

我缺少一个选项,如何使用
List
Immutable.js
获取
映射
函数中的索引号:

var list2=list1.map(mapper=>{a:mapper.a,b:mapper.index???}).toList();


map()
返回
Iterable
。有什么优雅的方法可以满足我的需要吗?

您可以通过第二个参数获得
map
方法当前迭代的
索引

示例:

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
const list=['h','e','l','l','o'];
list.map((元素,索引)=>{
log(“当前迭代为:”+索引);
log(“当前元素为:“+current元素”);
控制台日志(“\n”);
return currElement;//相当于列表[索引]
});
输出:

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
当前迭代为:0
当前元素为:h 当前迭代为:1
当前元素为:e 当前迭代为:2
当前元素为:l 当前迭代为:3
当前元素为:l 当前迭代为:4
当前元素为:o
另请参见:

参数

回拨- 函数,该函数生成新数组的元素,并带有三个参数:

1) 当前值
数组中正在处理的当前元素

2)指数
数组中正在处理的当前元素的索引。

3) 数组
已调用数组映射

Array.prototype.map()
索引: 可以通过回调函数的第二个参数访问索引
Array.prototype.map()
。以下是一个例子:

const数组=[1,2,3,4];
常量映射=数组.map((x,索引)=>{
控制台日志(索引);
返回x+索引;
});
控制台日志(map)使用Ramda:

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);
  • 假设您有一个数组,如
const arr=[1,2,3,4,5,6,7,8,9]
arr.map((myArr,索引)=>{
log(`您的索引是->${index},值是${myArr}`);

})
您想要什么并不明显。请记住,
map
应该保留数组的结构,也就是说,只转换数组的值,而不转换数组本身。map的回调函数是否应该始终具有return语句?“X”在代码中是什么意思?@HarshKanchina
map
操作用于通过迭代给定数组的元素来构造新数组。要回答您的问题,需要一个return语句,在这种情况下,它将在每次迭代中返回值“X”。因此,代码的最终产品将是
['X'、'X'、'X'、'X']
@但是没有在任何地方定义'X'。那么它指的是什么呢?函数如何知道X在这里指的是什么?@HarshKanchina
'X'
是一个字符串。我希望此索引以1开头,我如何实现这一点?