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

การหาความยาวคำเฉลี่ยในประโยค - JavaScript

คำนวณความยาวเฉลี่ยของคำในประโยค ปัดเศษ 2 ตำแหน่งทศนิยม

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

const str = 'This sentence will be used to calculate average word length';

const averageWordLength = str => {
  if (!str.includes(' ')) return str.length;

  const { length: strLen } = str;
  const { length: numWords } = str.split(' ');

  // strLen - (numWords - 1) = จำนวนตัวอักษรรวม (ลบช่องว่าง)
  const average = (strLen - numWords + 1) / numWords;
  return average.toFixed(2);
};

console.log(averageWordLength(str));      // 5.00
console.log(averageWordLength('test test')); // 4.00

ตรรกะการคำนวณ

  • strLen = ความยาวสตริงรวมช่องว่าง
  • numWords = จำนวนคำ
  • ช่องว่าง = numWords - 1
  • ตัวอักษรรวม = strLen - (numWords - 1) = strLen - numWords + 1
  • ค่าเฉลี่ย = ตัวอักษรรวม / numWords

วิธีที่ชัดเจนกว่า

const averageWordLength = str => {
  const words = str.split(' ').filter(w => w.length > 0);
  const totalChars = words.reduce((sum, w) => sum + w.length, 0);
  return (totalChars / words.length).toFixed(2);
};

ผลลัพธ์

5.00
4.00