ปัญหา
เราต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงของตัวอักษรอังกฤษ str เป็นอาร์กิวเมนต์เดียว ฟังก์ชันควรคืนค่า true หากและก็ต่อเมื่อสระและพยัญชนะปรากฏสลับกันในสตริงอินพุต false ในกรณีอื่น
ตัวอย่างเช่น หากอินพุตคือ
อินพุต
const str = 'amazon';
เอาต์พุต
const output = true;
คำอธิบายเอาต์พุต
เพราะสระและพยัญชนะปรากฏสลับกันในสตริง 'amazon'
ตัวอย่างโค้ด
const str = 'amazon';
const appearAlternatingly = (str = '') => {
return str.split('').every((v, i) => {
if (/[aeiou]/.test(str[0])) {
if (i % 2 === 0 && /[aeiou]/.test(v)) {
return true;
} else if (i % 2 !== 0 && !/[aeiou]/.test(v)) {
return true;
} else {
return false;
}
}
if (!/[aeiou]/.test(str[0])) {
if (i % 2 == 0 && !/[aeiou]/.test(v)) {
return true;
} else if (i % 2 !== 0 && /[aeiou]/.test(v)) {
return true;
} else {
return false;
}
}
});
};
console.log(appearAlternatingly(str));
ผลลัพธ์
true