강의

멘토링

커뮤니티

Cộng đồng Hỏi & Đáp của Inflearn

Hình ảnh hồ sơ của h5516545094
h5516545094

câu hỏi đã được viết

JavaScript Trung và Cao cấp: Cốt lõi của Engine

1. Hàm đệ quy, ngăn chặn liên kết thuộc tính, dạng hàm đệ quy, [thời gian dọn dẹp]

정리시간 질문입니다.

Viết

·

274

1

선생님 안녕하세요? 선생님 수업을 열심히 듣고있는 선생님의 팬입니다. 정리시간에 내주신 문제를 풀다가 배열의 값을 누적하는 부분이 해결이 안되서 isNaN() 함수를 통하여 해결하였는데 제가 제대로 문제를 푼것인지 모르겠어서 여쭤봅니다.

javascript

Câu trả lời 3

4

tonextday님의 프로필 이미지
tonextday
Người chia sẻ kiến thức

나름대로 스타일을 가진 경력자에게 "이것입니다"라고 제시하는 것이 좀 그래서 deep copy 코드를 게재합니다. 이것을 참조하고 console.log()에 출력하는 부분을 정리하면 될 것 같습니다. assign() 함수가 1차원 레벨은 연동되지 않지만, 한 단계 더 들어가면 연동이 됩니다. 그래서 deep copy 코드가 필요할 것 같아 게재합니다. 지면 관계상 주석은 작성하지 않았습니다. 제가 개발한 것으로 모든 환경에 맞지 않을 수 있습니다. ES5 기준이므로 ES6+를 적용하면 스타일이 달라질 수 있습니다. Point.deepCopy() 앞에 debugger를 걸고 따라가면서 오른쪽 창의 프로퍼티 값의 변화를 살펴보는 것도 하나의 재미입니다. 

var Point = {};
Point.member = {
  jan: {item: {title: "JS북", amount:100}, point: [10,20,30]},
  Feb: {item: {title: "JS북", amount:200}, point: [40,50,60]}
};
Point.dup = {};
Point.dupArray = function(target, dup){
  dup.forEach(function(element, index){
    if (Array.isArray(element)){
      if (!target[index]){
        target[index] = [];
      };
      this.dedpCopy(target[index], element);
    } else if (typeof element === 'object'){
      if (!target[index]){
        target[index] = {};
      };
      this.deepCopy(target[index], element);
    } else {
      target[index] = element;
    };
  }, this);
};
Point.dupObject = function(target, dup){
  for (var pty in dup){
    var value = dup[pty];
    if (Array.isArray(value)){
      if (!target[pty]){
        target[pty] = [];
      };
      this.deepCopy(target[pty], value);
    } else if (typeof value === 'object'){
      if (!target[pty]){
        target[pty] = {};
      };
      this.deepCopy(target[pty], value);
    } else {
      target[pty] = value;
    };
  };
};
Point.deepCopy = function(target, dup){
  if (Array.isArray(dup)){
    this.dupArray(target, dup);
  } else if (typeof dup === 'object'){
    this.dupObject(target, dup);
  };
};
Point.deepCopy(Point.dup, Point.member);

0

강사님, 저도 정리시간을 가지며 구현을 해봤는데, 올바르게한 것인지 고칠곳이 있다면 어떤 방향으로 고치면 좋을지 조언부탁드립니다!

var member = {
    jan: {item: {title: "JS북", amount:100}, point: [10,20,30]},
    Feb: {item: {title: "JS북", amount:200}, point: [40,50,60]},
}
var total = 0;
function reduce(arr){
    var result = arr.reduce((a,b)=>a+b);
    total += result;
    console.log(result);
}
function solution(data){
    for(const type in data){
        data[type] instanceof Array
            ?reduce(data[type])
            :typeof data[type] ==="object"
                ?solution(data[type])
                :console.log(type+":", data[type]);
    }
}
solution(member);
console.log(total);

0

tonextday님의 프로필 이미지
tonextday
Người chia sẻ kiến thức

조금 어색합니다만, 코딩 경험이 쌓이면 해결되므로 지금 상태도 괜찮습니다. 지금처럼 하나씩 정리하면서 나아가면 무엇이 어색한지 느낄 수 있습니다. 재귀함수는 종료 처리를 동반해야 합니다. debugger(break point)를 걸어서 코드를 한 줄씩 실행해 보세요. 이를 위해 코드를 분리하는 것도 하나의 방법입니다. 그런데 지금하려면 너무 복잡하고 힘드므로 우선 진행을 하고 다시 처음부터 들으면서 정리하는 것도 괜찮을 것 같습니다.

Hình ảnh hồ sơ của h5516545094
h5516545094

câu hỏi đã được viết

Đặt câu hỏi