เราจำเป็นต้องเขียนฟังก์ชัน 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' ]