[ERROR] typeerror: cannot read properties of undefined (reading 'push')

Mark·2022년 8월 11일
0
post-thumbnail

JavaScript 알고리즘을 푸는 과정에서 발생한 에러

1. 문제 상황

  • answer[i]로 값들을 push 하는 과정에서 발생한 에러이다.
function solution(arr1, arr2, signs) {
    let answer = [[]];

    for (let i=0; i<arr1.length; i++){
        console.log(answer[i]) // []

        for(let j=0; j<arr1[i].length; j++){
            if (signs[i][j] === false) {
                arr1[i][j] = (arr1[i][j]) * -1
                arr2[i][j] = (arr2[i][j]) * -1
            }
            console.log(arr1[i][j] + arr2[i][j]) // 10,8,-7,-9,8,-11
            answer[i].push(arr1[i][j] + arr2[i][j])
        }
    }
    return answer;
}
answer[i].push(arr1[i][j] + arr2[i][j])

2. 문제 해결

  • answer[i]가 undefined라서 push를 할 때 에러가 발생한 것 같다. answer[i]에 ([])(배열)을 할당해줌으로써 문제가 해결됐다.
answer[i] =[];

참고

profile
개인 공부 정리

0개의 댓글