如何获取我的JavaScript数组的所有子串(连续子序列)?

Int*_*eep 18 javascript arrays substring

我的任务是使用JavaScript将给定的数组拆分为更小的数组.例如[1, 2, 3, 4]应该拆分为[1] [1, 2] [1, 2, 3] [1, 2, 3, 4] [2] [2, 3] [2, 3, 4] [3] [3, 4] [4].

我正在使用此代码:

let arr = [1, 2, 3, 4];

for (let i = 1; i <= arr.length; i++) {
  let a = [];
  for (let j = 0; j < arr.length; j++) {
    a.push(arr[j]);
    if (a.length === i) {
      break;
    }
  }
  console.log(a);
}
Run Code Online (Sandbox Code Playgroud)

我得到以下结果: [1] [1, 2] [1, 2, 3] [1, 2, 3, 4] undefined

我错过了什么/做错了什么?

Nin*_*olz 16

对于内部数组,您可以从外部数组的索引开始.

var array = [1, 2, 3, 4],
    i, j, l = array.length,
    result = [];
    
for (i = 0; i < l; i++) {
    for (j = i; j < l; j++) {
        result.push(array.slice(i, j + 1));
    }
}
console.log(result.map(a => a.join(' ')));
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)


Ank*_*wal 11

您的代码中有两个问题:

  1. 您需要使用循环来初始化i内部循环的值,以便它考虑新迭代的下一个索引i
  2. 您需要删除break内循环中的长度.

let arr = [1, 2, 3, 4];
for (let i = 0; i <= arr.length; i++) {
  let a = [];
  for (let j = i; j < arr.length; j++) {
    a.push(arr[j]);
    console.log(a);
  }
}
Run Code Online (Sandbox Code Playgroud)