问题我们需要编写一个 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
以上就是在 javascript 中基于字符矩阵和数字数组构造字符串的详细内容。