본문 바로가기

열정가득한 개발자의 이야기/한땀 한땀 공부 내용 TIL

for making new Map in JS

반응형

hi.

today, I learned a new way for initialize the Map.

 

origin way is too long. like  this :

 

for(let i = 0; i < x.length; i++){

    if(a.has(x[i]){

          a.set(x[i], a.get(x[i]) + 1)

} else { a.set(x[i],1)

}

 

for counting the all of the elements in some array, I usually use map and counting them.

but today, I found out shorten that code. like this :

 

for(let i = 0; i < x.length; i++){

      a.set(x[i], a.get(x[i] || 0) + 1)

}

 

it will be working same with origin one.

for using '||' , I can get rid of the if statement. 

if the value is undefined, it will be converted to 0, 

 

fantastic!!

 

반응형