简体   繁体   English

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

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

I'm looking for a command that returns the index of an element so I can use it in map functions. 我正在寻找一个返回元素索引的命令,以便可以在地图函数中使用它。

Here's an example : 这是一个例子:

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}));
}

I'm sure there's a neater way with a command that would give me the element's index, but all my google searches have been fruitless so far. 我敢肯定,有一种更整洁的命令可以给我元素的索引,但是到目前为止,我所有的Google搜索都没有结果。

Second parameter in callback function is index you can use that 回调函数中的第二个参数是index您可以使用它

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

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

You can make it cleaner by three steps: 您可以通过三个步骤使它更清洁:

  • Use the second parameter of callback passed to map() which is index of element. 使用传递给map()的callback的第二个参数,它是element的索引。
  • Use arrow function and implicitly return the value 使用箭头函数并隐式返回值
  • Use Template Strings instead of + again and again. 一次又一次使用模板字符串而不是+

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

In your above code you have created a function which doesn't make any sense. 在上面的代码中,您创建了一个没有任何意义的函数。 That function should take an array as a parameter and then log the value of that particular arr. 该函数应将数组作为参数,然后记录该特定arr的值。

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

map already gives you the index. map已经给您索引。 The callback gets three parameters: 回调获取三个参数:

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

You don't need to declare all three (JavaScript isn't fussy about it), but they are there if you need them. 您无需声明所有这三个(JavaScript对此并不挑剔),但是如果需要它们,它们就在那里。

You could also simply use Array.from since its second argument is an Array.map : 您也可以简单地使用Array.from,因为它的第二个参数是Array.map

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

The overall idea is to use the 2nd parameter of map (which provides you with the current iteration index) and with that and the current value to construct your result. 总体思路是使用map的第二个参数(为您提供当前的迭代索引),并使用该参数和当前值来构造结果。

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

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