-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathShift-Polyfill.js
More file actions
32 lines (23 loc) 路 971 Bytes
/
Copy pathShift-Polyfill.js
File metadata and controls
32 lines (23 loc) 路 971 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/* 馃挕"JavaScript-with-JC"
馃憠Array.prototype.shift and Its Polyfill
The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.
馃挕Note - It mutates the original array, and returns first element.
馃憠 One Level Up :- We can create our own custom shift( Polyfill of shift ), Check out the code below.馃憞
*/
const numbers = [1, 2, 3, 4, 5];
const result = numbers.shift();
console.log("result", result); // 1
console.log("numbers", numbers); // [ 2, 3, 4, 5 ]
Array.prototype.customShift = function () {
let array = this;
let result = array[0];
for (let i = 0; i < this.length; i++) {
array[i] = array[i + 1];
}
array.length = array.length - 1;
return result;
};
const numbersCustom = [1, 2, 3, 4, 5];
const resultCustom = numbersCustom.customShift();
console.log("resultCustom", resultCustom); // 1
console.log("numbersCustom", numbersCustom); // [ 2, 3, 4, 5 ]