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

การนับจำนวนวงกลมในตัวอักษรภาษาอังกฤษด้วย JavaScript


ปัญหา

เราต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงของตัวอักษรภาษาอังกฤษ ฟังก์ชันควรนับจำนวนวงกลม (rings) ที่มีในสตริง

ตัวอักษร 'O', 'b', 'p', 'e', 'A' ฯลฯ มี 1 วงกลม ส่วน 'B' มี 2 วงกลม

ตัวอย่าง

โค้ดตัวอย่างดังนี้:

const str = 'some random text string';
function countRings(str){
  const rings = ['A', 'D', 'O', 'P', 'Q', 'R', 'a', 'b', 'd', 'e', 'g', 'o', 'p', 'q'];
  const twoRings = ['B'];
  let score = 0;
  str.split('').map(x => rings.includes(x)
    ? score++
    : twoRings.includes(x)
    ? score = score + 2
    : x
  );
  return score;
}
console.log(countRings(str));

ผลลัพธ์

7