เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงเป็นอาร์กิวเมนต์เดียว จากนั้นฟังก์ชันควรวนซ้ำในสตริงและค้นหาและส่งคืนคำที่ยาวที่สุดจากสตริง
ตัวอย่างเช่น −
หากสตริงอินพุตเป็น −
const str = 'Coding in JavaScript is really fun';
จากนั้นสตริงเอาต์พุตควรเป็น −
const output = 'JavaScript';
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const str = 'Coding in JavaScript is really fun';
const findLongest = (str = '') => {
const strArr = str.split(' ');
const word = strArr.reduce((acc, val) => {
let { length: len } = acc;
if(val.length > len){
acc = val;
};
return acc;
}, '');
return word;
};
console.log(findLongest(str)); ผลลัพธ์
ต่อไปนี้เป็นผลลัพธ์บนคอนโซล -
JavaScript