ปัญหา
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่ใช้ตัวเลข n(n>0) ฟังก์ชันของเราควรส่งคืนอาร์เรย์ที่มีส่วนต่อเนื่องของเลขคี่หรือเลขคู่ หมายความว่าเราควรแยกตัวเลขที่ตำแหน่งเมื่อเราพบตัวเลขที่แตกต่างกัน (คี่สำหรับคู่แม้แต่สำหรับคี่)
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const num = 124579;
const splitDifferent = (num = 1) => {
const str = String(num);
const res = [];
let temp = '';
for(let i = 0; i < str.length; i++){
const el = str[i];
if(!temp || +temp[temp.length - 1] % 2 === +el % 2){
temp += el;
}else{
res.push(+temp);
temp = el;
};
};
if(temp){
res.push(+temp);
temp = '';
};
return res;
};
console.log(splitDifferent(num)); ผลลัพธ์
[ 1, 24, 579 ]