我的任务是使用 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);
}
我得到以下结果:
[1] [1, 2] [1, 2, 3] [1, 2, 3, 4] undefined
我错过了什么/做错了什么?
最佳答案
对于内部数组,您可以从外部数组的索引开始。
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(' ')));
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 如何获取我的 JavaScript 数组的所有子字符串(连续子序列)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52363370/