Array.map:获取要在返回函数中使用的每个元素的索引 [英] Array.map : get the index of each element to use in the return function

查看:92
本文介绍了Array.map:获取要在返回函数中使用的每个元素的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm looking for a command that returns the index of an element so I can use it in map functions.

这是一个例子:

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搜索都没有结果.

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.

推荐答案

您可以通过以下三个步骤使它更干净:

You can make it cleaner by three steps:

  • 使用传递给 map()的回调的第二个参数,即元素的索引.
  • 使用箭头函数并隐式返回值
  • 一次又一次地使用模板字符串而不是 + .
  • Use the second parameter of callback passed to map() which is index of 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)

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

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.

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

这篇关于Array.map:获取要在返回函数中使用的每个元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆