第一种方法(推荐)
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));
console.log(sliceFixLenth(str,2));
console.log(sliceFixLenth(str,3));
第二种方法
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));