ปัญหา
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่ใช้ประโยคของคำและตัวเลข ฟังก์ชันควรส่งคืนอาร์เรย์ของคำทั้งหมดที่มากกว่าความยาวที่ระบุโดยตัวเลข
ป้อนข้อมูล
const str = 'this is an example of a basic sentence'; const num = 4;
ผลผลิต
const output = [ 'example', 'basic', 'sentence' ];
เนื่องจากเป็นเพียงสามคำที่มีความยาวมากกว่า 4
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const str = 'this is an example of a basic sentence';
const num = 4;
const findLengthy = (str = '', num = 1) => {
const strArr = str.split(' ');
const res = [];
for(let i = 0; i < strArr.length; i++){
const el = strArr[i];
if(el.length > num){
res.push(el);
};
};
return res;
};
console.log(findLengthy(str, num)); ผลลัพธ์
[ 'example', 'basic', 'sentence' ]