오늘은 tree ui를 해보려고 한다.
목적은 재귀함수를 사용하여서
마트료시카같은 계속 인형을 생선하는것인데
잘 모르겠다.

const menu = [
{
type: 'group',
name: '음료',
children: [
{
type: 'group',
name: '콜드 브루',
children: [
{ type: 'item', name: '나이트로 콜드 브루' },
{ type: 'item', name: '돌체 콜드 브루' },
{ type: 'item', name: '제주 비자림 콜드 브루' },
{ type: 'item', name: '콜드 브루' },
],
},
로 표현된다.
블로그를 찾아보았다.
https://dololak.tistory.com/675
근데 어려워서 생각해보니 고차함수를 다 안풀었다. 그래서 고차함수에 대해서 정리를 해보려고 한다.
그래서 forEach에 대해서 다시 한번 검색해보았다.
forEach
foreach 반복문은 오직 Array 객체에서만 사용가능한 메서드입니다. (ES6부터는 Map,Set 지원)
배열의 요소들을 반복하여 작업을 수행할수 있습니다.
foreach구문의 인자로 callback함수를 등록할수 있고, 배열의 각 요소들이 반복될 떄 이 callback 함수가 호출됩니다. callback 함수에서 배열요소의 인덱스와 값에 접근할수 있습니다.
var arr = ['가','나','다','라'];
arr.forEach(function(item,index,arr2){
console.log(item,index,arr2[index+1]);
})
첫번째 인수는 배열의 각각의 item
두번째 인수는 배열의 index
세번쨰 인수는 배열 그자체
_.each = function (collection, iteratee) {
if(Array.isArray(collection)) {
for (let i =0; i < collection.length ; i++) {
iteratee(collection[i], i , collection); /// 배열 일때
}
}else { /// 객체 일때
for (let key in collection) {
iteratee(collection[key], key, collection);
}
}
};
이거는 언더바때 했던것
collection[key]는 아이템이고
index key 이고
arr2[index+1] 은 collection인데
for .... in 반복문
객체에 사용 할수 있습니다.
객체의 key값과 value 값을 뽑아내는데 유용합니다.
객체의 키값의 갯수만큼 반복하여 첫번째 키값부터 마지막 키값까지 반복합니다.
var obj = { a: '가', b: '나', c: '다' };
for (var key in obj) {
console.log(key, obj[key]);
}
for ... of 반복문
var iterable = [10, 20, 30];
for (var value of iterable) {
console.log(value);
}
for in 반복문과 for of 반복문의 차이점
Object.prototype.objCustom = function () {};
// Object 프로퍼티에 객체 생성
Array.prototype.arrCustom = function () {};
// array 프로퍼티에 객체 생성
var iterable = [3, 5, 7];
iterable.foo = "hello";
for (var key in iterable) {
console.log(key);
// 0, 1, 2, "foo", "arrCustom", "objCustom"
} //기본 js 내장함수에 프로퍼티를 추가해서 프로퍼티까지 다뽑힌다
for (var value of iterable) {
console.log(value); // 3, 5, 7
}
https://jsdev.kr/t/for-in-vs-for-of/2938
렌더링
https://boxfoxs.tistory.com/408
const root = document.getElementById('root');
function createTreeView(menu, currentNode) { //// obejct랑 현재 있는 node
->menu.forEach(function(Obj) {
->for(let Obj of menu) {
forEach를 써도 되고 for 문을 돌려도 된다.
if(Obj.type ==='group') {
const liTag = document.createElement('li');
const checkboxInputTag = document.createElement('input');
checkboxInputTag.type = 'checkbox'
liTag.append(checkboxInputTag);
const menuSpanTag = document.createElement('span');
menuSpanTag.textContent = Obj.name;
liTag.append(menuSpanTag)
const nextUlTag =document.createElement('ul');
liTag.append(nextUlTag); //// currentNode는 parameter이다... 그러니까 지정하는데 갖다붙여 이거다..
currentNode.append(liTag); //// 지정해주는데다가 가져다가 붙여라
-> 포인트 재귀함수
createTreeView(Obj.children, nextUlTag);
-> 왜냐하면 다음 것을 node에 씌워줘야하니까.
}
if(Obj.type ==='item') {
-> 순회를 해서 다음으로 넘어갔어.
const liTag = document.createElement('li');
liTag.textContent=Obj.name;
currentNode.append(liTag);
}
});
}
createTreeView(menu, root);