首页 > 解决方案 > 在 JS 循环/数组中通过索引创建新值

问题描述

我有一个值数组:

let myArray = [ 'Ifmanwas',
  'meanttos',
  'tayonthe',
  'groundgo',
  'dwouldha',
  'vegivenu',
  'sroots' ]

我想为数组中的每个项目打印一个新值,以便第一项是零索引处所有字符的集合,第二项是 1 索引位置处所有字符的集合,等等...

因此,例如,第一个数组的输出将是“Imtgdvs”(所有位于(“0”)的字母,第二个将是“fearwer”(所有位于索引“1”的字母)等等......

我对如何做到这一点非常迷茫,并尝试了多种不同的方法,不胜感激。

对于这个简单的尝试,我为第一个实例创建了一个包含所有字母的数组:

function convertToCode(box) {


  let arr = [];
  for (i = 0; i < box.length; i++) {
    let counter = i;
    let index = box[counter];
    let letter = index.charAt(0);

    arr.push(letter);
  }
  console.log(arr);
}


convertToCode(myArray)

谢谢

标签: javascriptarraysnode.jsstringloops

解决方案


您的示例中的主要问题是:index.charAt(0);. 这将始终获得第一个字符,而您需要一个嵌套循环。

您可以Array.map()与 结合使用Array.reduce(),如下所示:

let myArray = ['Ifmanwas','meanttos','tayonthe','groundgo','dwouldha','vegivenu','sroots'];

const result = Array.from(myArray[0])                              //Create an array as long as our first string
  .map((l,idx) =>                                                  //Update each item in that array...
    myArray.reduce((out,str) => str[idx] ? out+str[idx] : out, "") //to be a combination of all letters at index [idx] from original array
  );

console.log(result);

请注意,这使用数组中的第一个字符串来决定要创建多少个字符串,而不是最长的字符串。


推荐阅读