Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การหา substring ทั้งหมดของสตริงแบบเรียกซ้ำ (Recursive) ใน JavaScript

เราต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงและสร้าง substring ทั้งหมดที่เป็นไปได้แบบเรียกซ้ำ (recursive) แล้วคืนอาร์เรย์ของ substring ทั้งหมด

ตัวอย่างโค้ด

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'
]