เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงและตัวเลข n (เพื่อให้ n หารความยาวของสตริงได้อย่างแม่นยำ) เราจำเป็นต้องคืนค่าอาร์เรย์ของสตริงที่มีความยาว n ที่มี n ส่วนเท่าๆ กันของสตริง
มาเขียนโค้ดสำหรับฟังก์ชันนี้กัน −
ตัวอย่าง
const str = 'this is a sample string';
const num = 5;
const divideEqual = (str, num) => {
const len = str.length / num;
const creds = str.split("").reduce((acc, val) => {
let { res, currInd } = acc;
if(!res[currInd] || res[currInd].length < len){
res[currInd] = (res[currInd] || "") + val;
}else{
res[++currInd] = val;
};
return { res, currInd };
}, {
res: [],
currInd: 0
});
return creds.res;
};
console.log(divideEqual(str, num)); ผลลัพธ์
ต่อไปนี้เป็นผลลัพธ์ในคอนโซล -
[ 'this ', 'is a ', 'sampl', 'e str', 'ing' ]