강의

멘토링

커뮤니티

Inflearn Community Q&A

shinetigerdev1516's profile image
shinetigerdev1516

asked

Introduction to Javascript Algorithm Problem Solving (Coding Test Preparation)

4. Calculating scores

cnt++와 cnt+=1의 차이점

Written on

·

1.5K

0

function solution(arr){         
  let answer=0;
  let cnt=0;

  for(let x of arr){
    if(x===1){
      console.log(cnt++)
      answer+=cnt;
    } else{cnt=0;}

  }
  return answer
}

let arr=[1, 0, 1, 1, 1, 0, 0, 1, 1, 0];
console.log(solution(arr));

선생님의 풀이에서 cnt++를 console.log로 찍어보면 

0,0,1,2,0,1 이 출력됩니다.

그러나 cnt++이 아니라 cnt+=1을 쓰면 1,1,2,3,1,2 로 정상적으로 출력되구요.

왜 이런 차이가 발생하는 걸까요? 

 

 

javascript코테 준비 같이 해요!

Answer 1

4

++cnt와 같이 ++연산을 앞에서 할 경우, 해당 라인에서 +1연산이 먼저 진행됩니다.

반대로 cnt++ 처럼 ++연산을 뒤에서 할 경우, 다음 라인으로 넘어가야 +1이 진행됩니다.

 

var num1 = 1

console.log(num1++) // num1은 현재 1입니다. 그러므로 num1은 1이 출력되고,

                                            // 다음줄로 넘어가야 2로 바뀌게 됩니다.

console.log(num1) // 이제서야 +1연산이 적용되서 num1은 2가 출력됩니다.

////////////////////////////

var num2 = 1

console.log(++num1) // ++연산을 앞에 붙일경우 해당 줄에서 +1연산을 먼저 진행합니다. 

                                            // 그러므로 num1은 현재2이며, num1은 2가 출력됩니다.

console.log(num1)   // 위에줄에서 +1이 진행되었으므로 num1은 2가 출력됩니다.

 

님이 쓴거에서도

for(let x of arr) {

    if(x === 1) {

        console.log(cnt++) // 다음줄로 넘어가야 ++연산이 진행되죠. 그러므로 아직 +1되지 않았습니다.

// 생략

반대로

for(let x of arr) {

    if(x === 1) {

        console.log(++cnt) // 해당줄에서 +1연산이 먼저진행되므로, 님이 원하는 결과가 나올것입니다.

 

알려주셔서 감사합니다!!! 

shinetigerdev1516's profile image
shinetigerdev1516

asked

Ask a question