¿Cómo accedo dinámicamente a los accesores de propiedades en javascript? Digamos que estoy construyendo una lista enlazada. Digamos que esta lista puede tener cualquier longitud y cambia dinámicamente.
var answerList = new ListNode(4); answerList.next = new ListNode(5); answerList.next.next = new ListNode(6); answerList.next.next.next = new ListNode(7);¿Cómo puedo hacer que esto vaya al 100 .siguiente sin hacer:
answerList.next.next.next.next.next.next.next.next.next.next.next.next.next.next.next.next.next.next.next.next.next.next.next.next.next.next.next.nextsi desea insertar 100 elementos en una LinkedList, haga
var head = new ListNode(0); var temp = head; // sets temp to head for(let i=1; i<100;i++){ temp.next = new ListNode(i); // links new nodes to temp temp = temp.next;} // at the end head->0->1->2..->98->99Puede lograr esto usando recursividad si pasa currLevel y finalLevel como:
function getValue(linkedList, currLevel, finalLevel) { if (currLevel === finalLevel) return linkedList?.value; return getValue(linkedList.next, currLevel + 1, finalLevel); } Debe manejar el caso en el que no haya tantos nodos que pase un número, entonces podría ser posible que no haya la propiedad .next en él, es decir, significa que es el último elemento en la lista vinculada. una de esas formas es como:
return (linkedList.next && getValue(linkedList.next, currLevel + 1, finalLevel)); class ListNode { constructor(val) { this.value = val; this.next = null; } } var answerList = new ListNode(4); answerList.next = new ListNode(5); answerList.next.next = new ListNode(6); answerList.next.next.next = new ListNode(7); function getValue(linkedList, currLevel, finalLevel) { if (currLevel === finalLevel) return linkedList?.value; return getValue(linkedList.next, currLevel + 1, finalLevel); } console.log(getValue(answerList, 0, 3));