สมมติว่าเรามีสตริงสองอาร์เรย์ อาร์เรย์แรกมี 12 สตริง หนึ่งสตริงสำหรับแต่ละเดือนของปีเช่นนี้ −
const year = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
อาร์เรย์ที่สองประกอบด้วยสตริงสองสตริงเท่านั้น ซึ่งแสดงถึงช่วงของเดือนเช่นนี้ −
const monthsRange = ["aug", "oct"];
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์สองอาร์เรย์ดังกล่าว จากนั้นฟังก์ชันควรเลือกเดือนทั้งหมดจากอาร์เรย์แรกที่อยู่ในช่วงที่ระบุโดยอาร์เรย์ช่วงที่สอง
เช่นเดียวกับอาร์เรย์ด้านบน ผลลัพธ์ควรเป็น −
const output = ['aug', 'sep'];
โปรดทราบว่าเราละเว้นองค์ประกอบปิดของช่วง ('oct') ในเอาต์พุต ซึ่งเป็นส่วนหนึ่งของฟังก์ชันการทำงาน
ตัวอย่าง
const year = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']; const range = ['aug', 'dec'];
const getMonthsInRange = (year, range) => {
const start = year.indexOf(range[0]);
const end = year.indexOf(range[1] || range[0]);
// also works if the range is reversed if (start <= end) {
return year.slice(start, end);
}
else {
return year.slice(start).concat(year.slice(0, end));
};
return false;
};
console.log(getMonthsInRange(year, range)); ผลลัพธ์
และผลลัพธ์ในคอนโซลจะเป็น −
[ 'aug', 'sep', 'oct', 'nov' ]