हमें एक 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