สมมติว่าเราต้องเขียนเมธอดอาร์เรย์ที่เขียนทับ Array.prototype.slice() ปกติเมธอด Array.prototype.slice() จะรับอาร์กิวเมนต์สองตัวคือดัชนีเริ่มต้นและดัชนีสิ้นสุด แล้วคืนค่าสับอาร์เรย์ของอาร์เรย์ต้นฉบับจากดัชนี start ถึง end-1
สิ่งที่เราต้องการคือทำให้ slice() ทำงานโดยคืนค่าสับอาร์เรย์จากดัชนี start ถึง end (ไม่ใช่ end-1) โค้ดสำหรับทำเช่นนี้แสดงด้านล่าง เราวนลูปผ่านอาร์เรย์ด้วย for loop ซึ่งเร็วกว่าเมธอดอาร์เรย์อื่นๆ จากนั้นคืนค่าสับอาร์เรย์ที่ต้องการ และสุดท้ายเขียนทับ Array.prototype.slice() ด้วยเมธอดที่เราเขียนเอง
ตัวอย่าง
const arr = [5, 5, 34, 43, 43, 76, 78, 3, 23, 1, 65, 87, 9]; const slice = function(start = 0, end = this.length-1){ const part = []; for(let i = start; i <= end; i++){ part.push(this[i]); }; return part; }; Array.prototype.slice = slice; console.log(arr.slice(0, 4)); console.log(arr.slice(5, 8)); console.log(arr.slice());ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็นดังนี้
[ 5, 5, 34, 43, 43 ] [ 76, 78, 3, 23 ] [ 5, 5, 34, 43, 43, 76, 78, 3, 23, 1, 65, 87, 9 ]