En alguna variable llamada a, quiero almacenar el contenido de un par de paréntesis de una variable llamada ecuación. Tengo una matriz llamada apertura que marca el índice de los corchetes de apertura.
let equation = '2(x(4-5x)(4-x))+10' let opening = [9,3,1,0] let a = '' for(let x = equation[opening[0]]; x != ')'; x++) { a += x; }esto conduce a un bucle infinito.
for(let x = equation[opening[0]]; x < equation.length; x++) { if (x == ')') {break;} a += x; }esto no condujo a un bucle infinito, pero la variable a permaneció como una cadena vacía.
Quiero que el resultado sea a = '4-x'
Ponga a+= x entre paréntesis antes del descanso
Bien. Esto fue tan divertido que escribí una página HTML con JavaScript...
https://highdex.net/parse_eq.htm
Puede ver la fuente y ver todo el código, pero en caso de que alguna vez elimine esa página, también pondré aquí solo la función de JavaScript...
//this function takes an equation and breaks it into parts based on parentheses. //it returns an array of the parts, where and equation like "4 * (8 - 1) / 4" would come back like... // index 0: "4 * [1] / 4" // index 1: "8 - 1" //Any number shown in brackets is a reference to the index that holds what goes in that place, so you can rebuild the equation if you want. function parseEquation(srcEq) { let parts = [""]; let nextIndex = 0; //holds the next index we'll use inside those brackets let currentIndex = 0; //holds the current index we're adding characters to let backToArray = [0]; //holds the index that we need to go back to when the parentheses close let srcLen = srcEq.length; for (let i = 0; i < srcLen; i++) { let currentChar = srcEq[i]; if (currentChar == "(") { //in this case we need to put the placeholder into the current index that references the next index, and then bump up the current index if (parts.length -1 < currentIndex) { parts.push(""); } nextIndex++; parts[currentIndex] += "[" + nextIndex + "]"; backToArray.push(currentIndex); currentIndex = nextIndex; } else if (currentChar == ")") { //in this case we need to drop the current char back down a level currentIndex = backToArray.pop(); } else { //in this case we just add the current character to the current array at the current index if (parts.length -1 < currentIndex) { parts.push(""); } parts[currentIndex] += currentChar; } } return parts; }