Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Javascript

รับตัวเลข n จากอาร์เรย์โดยเริ่มจากจุดที่กำหนด JavaScript


เราต้องเขียนฟังก์ชันอาร์เรย์ (Array.prototype.get()) ที่รับอาร์กิวเมนต์สามตัวก่อน ตัวเลข n ตัวที่สองเป็นตัวเลข พูด m (m <=array length-1) และวินาทีเป็นสตริง ที่สามารถมีค่าใดค่าหนึ่งจากสองค่า - 'ซ้าย' หรือ 'ขวา'

ฟังก์ชันควรส่งคืนอาร์เรย์ย่อยของอาร์เรย์ดั้งเดิมที่ควรมี n องค์ประกอบโดยเริ่มจากดัชนี m และในทิศทางที่กำหนด เช่น ซ้ายหรือขวา

ตัวอย่างเช่น −

// if the array is:
const arr = [0, 1, 2, 3, 4, 5, 6, 7];
// and the function call is:
arr.get(4, 6, 'right');
// then the output should be:
const output = [6, 7, 0, 1];

เรามาเขียนโค้ดของฟังก์ชันนี้กันดีกว่า −

ตัวอย่าง

const arr = [0, 1, 2, 3, 4, 5, 6, 7];
Array.prototype.get = function(num, ind, direction){
   const amount = direction === 'left' ? -1 : 1;
   if(ind > this.length-1){
      return false;
   };
   const res = [];
   for(let i = ind, j = 0; j < num; i += amount, j++){
      if(i > this.length-1){
         i = i % this.length;
      };
      if(i < 0){
         i = this.length-1;
      };
      res.push(this[i]);
   };
   return res;
};
console.log(arr.get(4, 6, 'right'));
console.log(arr.get(9, 6, 'left'));

ผลลัพธ์

ผลลัพธ์ในคอนโซลจะเป็น -

[ 6, 7, 0, 1 ]
[
   6, 5, 4, 3, 2,
   1, 0, 7, 6
]