javascript - 数组.map : get the index of each element to use in the return function

标签 javascript arrays google-apps-script

<分区>

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

这是一个例子:

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

我确信有一个更简洁的方法可以通过命令给我元素的索引,但到目前为止我所有的谷歌搜索都没有结果。

最佳答案

你可以通过三个步骤让它变得更干净:

  • 使用传递给 map() 的回调的第二个参数,它是元素的索引。
  • 使用箭头函数并隐式返回值
  • 一次又一次地使用模板字符串代替+

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])

关于javascript - 数组.map : get the index of each element to use in the return function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56268300/

相关文章:

javascript - 如何获取回车键以在JavaScript中提交表单

javascript - 如何使用桌面浏览器测试触摸事件?

javascript - 更新数组的一项

javascript - Google 脚本不会返回 Google 电子表格中的超链接

javascript - 通过一个术语搜索整个表

python - Numpy:获取索引大于值且条件为真的数组

c++ - 如何在循环中获取数组的大小

objective-c - 结构体中的结构体数组 [Objective-c]

google-apps-script - 用于复制非事件工作表的 Google 脚本

google-apps-script - GmailApp.getAliases() 返回一个空白列表