#2011

Donghee Choi·2023년 1월 6일

leetcode

목록 보기
7/13

2011. Final Value of Variable After Performing Operations

내 답안

/**
 * @param {string[]} operations
 * @return {number}
 */
var finalValueAfterOperations = function(operations) {
    let sum = operations.reduce((acc, item) => {
    if (item.includes('+')) {
      return acc + 1;
    } else {
      return acc - 1;
    }
  }, 0);

  return sum;
};

다른 답안

const finalValueAfterOperations = 
	(operations) => operations.
    	reduce((acc, curr) => curr[1] === "+" ? ++acc : --acc, 0)

첨언

왜 후위연산자(acc++)를 쓰지않고 선위연산자(++acc)를 쓰는가?
후위연산자를 쓰게되면 연산을하지만 연산하기전의 값이 return된다.
선위연산자를 쓰게되면 연산을하고 연산하고난후의 값이 return된다.

profile
frontend, vuejs, react, docker, kubernetes

0개의 댓글