Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การคืนค่าคำที่ยาวกว่าความยาวที่กำหนดจากสตริงใน JavaScript


ปัญหา

เราต้องเขียนฟังก์ชัน JavaScript ที่รับประโยค (sentence) และตัวเลข ฟังก์ชันควรคืนค่าเป็นอาร์เรย์ของคำทั้งหมดที่มีความยาวมากกว่าตัวเลขที่กำหนด

อินพุต

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' ]