Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

แบ่งสตริงเป็นส่วนๆ ใน JavaScript

เราต้องเขียนฟังก์ชันที่รับสตริงและตัวเลข n (โดยที่ n หารความยาวสตริงลงตัว) และคืนค่าอาร์เรย์ของสตริงความยาว n ที่มี n ส่วนเท่ากันของสตริง

ตัวอย่าง

โค้ดสำหรับนี้:

const str = 'we will be splitting this string into parts'; const num = 6; 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));

ผลลัพธ์

ผลลัพธ์ในคอนโซล:

[ 'we will ', 'be split', 'ting thi', 's string', ' into pa', 'rts' ]