簡體   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