第一种方法(推荐)
function sliceFixLenth(str,length) {
const result = [];
for (let i = 0; i <str.length ; i+=length) {
result.push(str.slice(i,i+length));
}
return result;
}
let str = "helloworld"
console.log(sliceFixLenth(str,1)); // ['h', 'e', 'l', 'l','o', 'w', 'o', 'r','l', 'd']
console.log(sliceFixLenth(str,2));// [ 'he', 'll', 'ow', 'or', 'ld' ]
console.log(sliceFixLenth(str,3));// [ 'hel', 'low', 'orl', 'd' ]
第二种方法
作为拓展
function sliceFix(str,length) {
const count = Math.ceil(str.length / length);
let start = 0;
let end = 0;
const result = [];
for (let index = 0; index < count; index++) {
end += length;
result.push(str.slice(start,end))
start += length;
}
return result;
}
console.log("sliceFix",sliceFixLenth(str,3));