// 배열의 모든 인스턴스가 사용할 수 있어야 한다. // 기존의 push와 동일한 동작을 할 수 있어야 한다. // push는 마지막 요소를 밀어 넣고 length를 반환한다. Array.prototype.myPush = function (...args) { // args에 값이 배열로 넘어온다. for (let i = 0; i < args.length; i++) { this[this.length] = args[i]; } return this.length; }; let arr = []; arr.myPush(1, 2, 3); console.log(arr); console.log(arr.length); // myPush는 배열의 모든 인스턴스가 사용할 수 있어야 한다. => Array.prototype에 위치해야 한다. // 함수의 인자는 몇 개가 들어오는지 알 수 없기때문에 가변인자를 사용해야 한다. // arguments는 비표준이므로 rest parameter를 쓰기로 한다. // 배열의 마지막 요소는 arr[arr.length]로 찾을 수 있다. // args 배열의 요소를 하나씩 순회하면서 삽입해줘야 한다. // pop 따라하기 // 조건 /* 모든 배열이 사용할 수 있어야 한다. 가장 마지막 요소를 제거하고 제거한 요소를 반환한다. */ // 1. array.prototype에 메서드가 와야 한다. // 2. this의 가장 마지막 요소를 삭제한다. // Array.prototype.myPop = function () { this.length = this.length - 1; return this[this.length - 1]; } let array = [1, 2]; console.log(array.myPop()); let p = [1, 2, 2, 3]; let res = {}; for (let i = 0; i < p.length; i++) { } Array.prototype.myForEach = function (callback, thisArg) { if (typeof callback !== 'function') { throw new TypeError(`${callback} is not a function`); } thisArg = thisArg || globalThis; for (let i = 0; i < this.length; i++) { callback.call(thisArg, this[i], i, this); } }; const arr = [1, 2, 3]; arr.myForEach((v, i, arr) => { console.log((v, i, arr)); }); Array.prototype.myForEach = function (callback, thisArg) { if (typeof callback !== 'function') { throw new TypeError(`${callback} is not a function`); } thisArg = thisArg || globalThis for (let i = 0; i < this.length; i++) { callback(thisArg, this[i], i, this); } }; const arr = [1, 2, 3]; arr.myForEach((v, i, arr) => { console.log((v, i, arr)); });