TypeError: Cannot read properties of undefined (reading 'replace')가 뜰 때....

임성은·2023년 2월 25일
0

제목 그대로 저 오류가 떴을때 해결방법(제가 통한 방법)

1. if문.

let array = JSON.stringify(question.questionBody);

  	let post = undefined;
    
   if (chk_array) {
     post = chk_array.replace(/"/g, '');
  }

if문을 써주지 않고 post에 바로 넣어줬을땐 undefind로 인해 타입에러가 떴지만 난 첫번째 방법으로 해결을 했습니다.

2. Optional chaining 사용

예를 그대로 가져 왔는데요

const str = undefined;

const result = str?.replace('old', 'new');

console.log(result); // undefined

2번으로 해결한 코드도 본 적이 있습니다.

3. 폴백 값에서 replace() 호출

null 병합 연산자 ( )를 사용하여 ??호출할 폴백 값을 제공 할 수 있습니다 replace().

const str = undefined;

const result = (str ?? 'old str').replace('old', 'new');

console.log(result); // 'new str'
null 병합 연산자( )는 또는 가 ??아닌 경우 왼쪽에 있는 값을 반환합니다 . 그렇다면 오른쪽에 있는 값을 반환합니다.nullundefined??

console.log(5 ?? 10); // 5
console.log(undefined ?? 10); // 10

4. replace()를 호출하는 대신 폴백 결과 사용

선택적 연결 연산자( ?.)와 null 병합 연산자( ??)를 결합하여 교체를 수행하는 대신 결과로 사용할 폴백 값을 제공할 수 있습니다.

const str = undefined;

const result = str?.replace('old', 'new') ?? 'no matches';

console.log(result); // 'no matches'

밑에 해결방법을 쓰기도 전에 이미 해결이 되었던 터지만, 1번 2번 선에서 해결 되면 좋겠습니다~

그 외는 replace 함수가 아닌 호출하는 요소의 id와 클래스네임을 확인해서 문제를 찾아 해결했다는 얘기도 봤습니다...!

출처:https://codingbeautydev.com/blog/javascript-cannot-read-property-replace-of-undefined/

profile
개발자의 길에 당차게 들어서다!!

0개의 댓글