เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงของสตริงที่เชื่อมด้วยช่องว่าง ฟังก์ชันควรคำนวณและส่งกลับความยาวเฉลี่ยของคำทั้งหมดที่อยู่ในสตริงที่ปัดเศษทศนิยมสองตำแหน่ง
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
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(' ');
const average = (strLen - numWords + 1) / numWords;
return average.toFixed(2);
};
console.log(averageWordLength(str));
console.log(averageWordLength('test test')); ผลลัพธ์
ต่อไปนี้เป็นผลลัพธ์ในคอนโซล -
5.00 4.00