์ฅ๋ฐ๊ตฌ๋์ ์ํ์ด ์์ต๋๋ค.
home2 › ๊ฒ์ํ › JavaScript, TS ๊ฒ์ํ › prototype ์ฐ์ต๋ฌธ์
์ ์๋ ์ ๋ ๋ง์ง๋ง ๋ฌธ์ ๋ฅผ
Array.prototype.remove3 = function(){ arr.forEach(i => { if(i == 3) { this.splice(i,1); } }); }
var arr = [1,2,3]; arr.remove3(); console.log(arr);
์ด๋ ๊ฒ foreach๋ฌธ ๋๋ ธ๋๋ฐ ์๋์ค๋ค์ ใ ใ ๋ญใ ๊ฐ๋ฌธ์ ์ผ๊ฐ์ฌ
remove3() ์์์ ์ฐ๊ณ ์๋ arr ๋ผ๋ ๋ณ์๊ฐ ์๋ฏธํ๋๋ฐ๊ฐ ์๋ฌด๊ฒ๋ ์์ด์ ๊ทธ๋ฐ๋ฏ์
this๋ก ๋ฐ๊พธ๋ ๊ฐ ํด๋ด ์๋ค
ํ์ค ๊ฐ์ฌํฉ๋๋ค ๋ฐ๋ณด๊ฐ์ ์ง์ ํ๋ค์ฌ
์ ์๋ ใ ใ arr์ this ๋ก ๋ฐ๊ฟจ๋๋ฐ๋ ์๋ผ๋ ์ด์ ๋ ๋ชฐ๊น์ฌ..
Array.prototype.remove3 = function(){ console.log(this); this.forEach(i => { if(i === 3) { this.splice(i,1); } }) }
let arr1 = [1,2,3] arr1.remove3(); console.log(arr1);
this.forEach((a,i) => { if(a === 3) { this.splice(i,1); } });
splice ํจ์ ์ฌ์ฉ๋ฒ์ด ์ด์ํ๋ฏํฉ๋๋ค