Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Tính độ dài trung bình từ trong câu - JavaScript

Viết hàm tính độ dài trung bình của các từ trong câu, làm tròn 2 chữ số thập phân.

Ví dụ

Câu: 'This sentence will be used to calculate average word length'

Tổng ký tự (kể khoảng trắng): 56, Số từ: 10, Khoảng trắng: 9

Trung bình = (56 - 9) / 10 = 4.7 → 4.70

Giải pháp

Mã triển khai:

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

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

console.log(averageWordLength(str));
console.log(averageWordLength('test test'));

Kết quả

Đầu ra trong console:

5.00
4.00

Sửa lỗi code gốc: Code gốc dùng công thức (strLen - numWords + 1) / numWords sai. Cách đúng: tổng độ dài từ / số từ.