我有一个数字列表,它是使用循环的字符串值,我想将此字符串拆分为数组中的不同变量,第一个长度为 3,第 6 个长度为 7,最后一个长度为 3。这可以使用函数和循环来完成。
最佳答案
我们可以这样做:
let str = '000111111122222223333333444444455555556666666mmmm';
// Defines the lengths we're using
let lengths = [3,7,7,7,7,7,7,3];
let index = 0;
let result = lengths.reduce((acc,n) => {
acc.push(str.slice(index, index += n));
return acc;
} , [])
console.log(result);
关于javascript - 使用函数和循环拼接字符串值并存储为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51910212/