递归获取JavaScript中字符串的所有子字符串
我们需要编写一个将字符串作为唯一参数的JavaScript函数。该函数应递归构造输入字符串的所有可能的子字符串。
然后,该函数应返回一个包含所有子字符串的数组。
示例
const str = 'example';
const buildSubstrings = (str = '') => {
let i, j;
const res = [];
for (i = 0; i < str.length; i++) {
for (j = i + 1; j < str.length + 1; j++) {
res.push(str.slice(i, j));
};
};
return res;
};
console.log(buildSubstrings(str));输出结果
控制台中的输出将是-
[ 'e', 'ex', 'exa', 'exam', 'examp', 'exampl', 'example', 'x', 'xa', 'xam', 'xamp', 'xampl', 'xample', 'a', 'am', 'amp', 'ampl', 'ample', 'm', 'mp', 'mpl', 'mple', 'p', 'pl', 'ple', 'l', 'le', 'e' ]
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短