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

JavaScript Get English Count Number (ลำดับที่ภาษาอังกฤษ)

เราต้องเขียนฟังก์ชัน JavaScript ที่รับตัวเลขและคืนค่าลำดับที่ภาษาอังกฤษสำหรับมัน

ตัวอย่าง:

3 returns 3rd

โค้ดสำหรับเรื่องนี้จะเป็น:

const num = 3;
const englishCount = num => {
  if (num % 10 === 1 && num % 100 !== 11) {
    return num + "st";
  }
  if (num % 10 === 2 && num % 100 !== 12) {
    return num + "nd";
  }
  if (num % 10 === 3 && num % 100 !== 13) {
    return num + "rd";
  }
  return num + "th";
};
console.log(englishCount(num));
console.log(englishCount(111));
console.log(englishCount(65));
console.log(englishCount(767));

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

3rd 111th 65th 767th