繁体   English   中英

Array.map:获取要在返回函数中使用的每个元素的索引

[英]Array.map : get the index of each element to use in the return function

我正在寻找一个返回元素索引的命令,以便可以在地图函数中使用它。

这是一个例子:

function myFunction() {
  var a = [4,7,9];
  //Looking for a way to return ["index 0 : 4", "index 1 : 7", "index 2 : 9"]
  //Only workaround found so far :
  var i = -1;
  Logger.log(a.map(function(el) {i++; return "index " + i + " : " + el}));
}

我敢肯定,有一种更整洁的命令可以给我元素的索引,但是到目前为止,我所有的Google搜索都没有结果。

回调函数中的第二个参数是index您可以使用它

  Array.map((value,index,this))

 function myFunction() { var a = [4,7,9]; console.log(a.map((v,i)=> "index " + i + " : " + v)); } myFunction() 

您可以通过三个步骤使它更清洁:

  • 使用传递给map()的callback的第二个参数,它是element的索引。
  • 使用箭头函数并隐式返回值
  • 一次又一次使用模板字符串而不是+

 var a = [4,7,9]; let res = a.map((x,i) => `index ${i} : ${x}`); console.log(res) 

在上面的代码中,您创建了一个没有任何意义的函数。 该函数应将数组作为参数,然后记录该特定arr的值。

 const myFunction = arr => console.log(arr.map((x,i) => `index ${i} : ${x}`)); myFunction([4,7,9]) 

map已经给您索引。 回调获取三个参数:

a.map(function(element, index, array) {return "index " + index + " : " + element})

您无需声明所有这三个(JavaScript对此并不挑剔),但是如果需要它们,它们就在那里。

您也可以简单地使用Array.from,因为它的第二个参数是Array.map

 console.log(Array.from([4,7,9], (x, i) => `index ${i} : ${x}`)) 

总体思路是使用map的第二个参数(为您提供当前的迭代索引),并使用该参数和当前值来构造结果。

暂无
暂无

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

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