JavaScript中基于字符矩阵和数字数组构造字符串
问题
我们需要编写一个JavaScript函数,该函数接受一个n*n字符串字符矩阵和一个整数数组(正数和唯一数)。
我们的函数应该构造一个字符串,其中包含从1开始的索引存在于数字数组中的那些字符。
字符矩阵-
[ [‘a’, ‘b’, ‘c’, d’], [‘o’, ‘f’, ‘r’, ‘g’], [‘h’, ‘i’, ‘e’, ‘j’], [‘k’, ‘l’, ‘m’, n’] ];
数字数组-
[1, 4, 5, 7, 11]
应该返回'adore',因为这些字符出现在由矩阵中的数字数组指定的基于1的索引处。
示例
以下是代码-
const arr = [ ['a', 'b', 'c', 'd'], ['o', 'f', 'r', 'g'], ['h', 'i', 'e', 'j'], ['k', 'l', 'm', 'n'] ]; const pos = [1, 4, 5, 7, 11]; const buildString = (arr = [], pos = []) => { const flat = []; arr.forEach(sub => { flat.push(...sub); }); let res = ''; pos.forEach(num => { res += (flat[num - 1] || ''); }); return res; }; console.log(buildString(arr, pos));输出结果
以下是控制台输出-
adore