简体   繁体   English

数组“映射”

[英]Array “mapping”

If I have an array of items, for example: 如果我有一个项目数组,例如:

var names = ['Rita', 'Sarah', 'Lisa', 'Joe', 'Ralph', 'Linda', 'Richard', 'Chris'];

And I have an array of numbers, for example: 我有一系列数字,例如:

var numbers = [2, 3, 5, 7];

How would I use these numbers to act as order numbers to get specific names? 我怎么会用这些数字来作为订单号得到具体的名字?


What I mean by that? 我的意思是什么?

Have a function that takes those two arrays and gives me an output: 有一个函数,它接受这两个数组并给我一个输出:

output = ['Lisa', 'Joe', 'Linda', 'Chris'];

Does JavaScript have any specific functions for that or would I need to code something myself? JavaScript是否具有任何特定功能,或者我需要自己编写代码?

Use map() for that 使用map()

 var names = ['Sarah', 'Lisa', 'Joe', 'Ralph', 'Linda', 'Richard', 'Chris']; var numbers = [2, 3, 5, 7]; var res = numbers.map(function(v) { return names[v - 1] }) // with ES6 arrow function // var res = numbers.map(v => names[v - 1]); document.write('<pre>' + JSON.stringify(res, null, 3) + '</pre>'); 


Or using filter() 或者使用filter()

 var names = ['Sarah', 'Lisa', 'Joe', 'Ralph', 'Linda', 'Richard', 'Chris']; var numbers = [2, 3, 5, 7]; var res = names.filter(function(v, i) { return numbers.indexOf(i + 1) > -1; }) // with ES6 arrow function // var res = numbers.filter((v, i) => numbers.indexOf(i + 1) > -1); document.write('<pre>' + JSON.stringify(res, null, 3) + '</pre>'); 

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

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