javascript - 在 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)
谢谢
解决方案
您的示例中的主要问题是: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);
请注意,这使用数组中的第一个字符串来决定要创建多少个字符串,而不是最长的字符串。
推荐阅读
- installation - 在应用 ./configure 命令安装 omnetpp 时,我收到关于在 $PATH 中找不到 C 编译器的消息
- python - 使用 h5py 读取和解码 hdf5 字符串
- android - 未解决的参考:viewModels()
- json - SQL 到 JSON - 创建一个 Json 数组
- python - 朴素贝叶斯 NLTK 交叉验证
- reactjs - 我在 React-Admin(打字稿)中找不到“资源”类型
- azure - 将时间戳传递给 azure 映射数据流
- php - Codeigniter:三个表之间的连接
- swift - Swift 5.2 闭包中的元组解构具有不一致的行为
- c# - EF Core 在调用中获取字符串的一部分