Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

317
Visualizações
Aplicación web Google Apps Script. Use una variable fuera de una declaración if forEach

Soy nuevo en Javascript, pensé que iba bien, pero no puedo resolver este problema.

Estoy usando el script de Google Apps para obtener datos de mi documento de Hojas de cálculo de Google y si un nombre en la columna A coincide con "Varios", entonces muestro el precio en la Columna B.

Mi secuencia de comandos funciona cuando uso la alerta dentro de la función if forEach, pero cuando muevo la alerta fuera de ella, se rompe. Lanzo alertas que dicen indefinido, indefinido, indefinido, el precio correcto y luego indefinido, indefinido nuevamente.

Supongo que tiene algo que ver con forEach, pero no sé cómo hacerlo.

Aquí está la sección del script que es mi problema.

 document.addEventListener("DOMContentLoaded", afterSidebarLoads); //get the data from Google Sheets function getRates() { const sheet = SpreadsheetApp.openById("fwffwfwefewdwedwedwedwedwedwedwed").getSheetByName("tab name"); return sheet.getRange(15, 1, sheet.getLastRow()-14, 2).getValues(); } // runs the script function afterSidebarLoads() { // Function Part: 1 google.script.run.withSuccessHandler(getSundriesyRate).getRates(); } // here's my problem function getSundriesyRate(arrayOfArrays){ // Function Part: 2 var sundriesRate = document.getElementById("sundries-rate"); arrayOfArrays.forEach(function(r){ // r= one of the lines in the aray var div = document.createElement("div"); if (r[0] === "Sundries") { // this does match var dhello = r[1].toLocaleString("en-GB", {style: "currency", currency: "GBP", minimumFractionDigits: 2}); alert(dhello); // works } else { } alert(dhello); // doesn't work }); }

Gracias

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Creando una variable fuera del bucle forEach y pasando el valor a la variable. entonces podrá usar esta variable fuera del ciclo. Si espera devolver varios valores, debe usar una matriz o diccionarios para almacenar los datos.

 document.addEventListener("DOMContentLoaded", afterSidebarLoads); //get the data from Google Sheets function getRates() { const sheet = SpreadsheetApp.openById("fwffwfwefewdwedwedwedwedwedwedwed").getSheetByName("tab name"); return sheet.getRange(15, 1, sheet.getLastRow()-14, 2).getValues(); } // runs the script function afterSidebarLoads() { // Function Part: 1 google.script.run.withSuccessHandler(getSundriesyRate).getRates(); } // here's my problem function getSundriesyRate(arrayOfArrays){ // Function Part: 2 var sundriesRate = document.getElementById("sundries-rate"); var dhello; arrayOfArrays.forEach(function(r){ // r= one of the lines in the aray var div = document.createElement("div"); if (r[0] === "Sundries") { // this does match dhello = r[1].toLocaleString("en-GB", {style: "currency", currency: "GBP", minimumFractionDigits: 2}); alert(dhello); // works } else { } //alert(dhello); // doesn't work (it's return undefined because in this forEach loop, it will go through every line of the array and it does not find the match , it returns nothing.) }); alert(dhello); // you can access this variable here. }
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda