본문 바로가기
JavaScript/메소드

[javascript] 스트링으로 된 수식 계산 eval, new Function

by Angry Stock 2023. 7. 2.
반응형
eval() 함수는 공식 홈페이지에서 취약점을 소개하고 절대 사용하지 말 것을 강조한다.
대체 함수로는
new Function 이 있다.
커뮤니티 등 검색을 해보면 eval() 함수를 쓸 상황은 나오지 않는다고 한다.
function solution1(string) {
  return eval(string);
}

function solution2(string) {
  return new Function('return ' + string)();
}

const string = ['4 + 444', '1 - 2222', '5 * 123', '123/ 3567'];

for (let i = 0; i < string.length; i++) {
  console.log('solution1', solution1(string[i]));
  console.log('solution2', solution2(string[i]));
}
반응형

댓글