• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Pruebas Online
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

180
Vistas
Why is this for loop logging correctly, but write to sheet wrongly using GAS?

I'm running this for loop and modifying some values on the go. It logs the values changed correctly in each iteration, but it repeats the last iteration when writing to sheets.

const rngList = cadSheet.getRangeList(dataRng).getRanges();

  //Gets the ranges' values and push them into an array;
  let values = [];
  for (let i = 0; i < rngList.length; i++) {
    values = [].concat(values, rngList[i].getValues().flat());
    //values.push([rngList[i].getValue()]);
  }

  let itens = [];
  for (let a = 0; a < tamanhosEscArr.length; a++) {
    for (let r = 0; r < coresEscArr.length; r++) {
      values[4] = variacao++;//Increments an ID number
      values.splice(29, 1); //removes this element
      values.splice(29, 0, tamanhosEscArr[a]); //inserts size being iterated over

      values.splice(30, 1);//removes this element
      values.splice(30, 0, coresEscArr[r]); //inserts color being iterated over

      Logger.log('Item: ' + values) //logs all 18 or so items, with their corresponding sizes and colors
      itens.push(values);
    }
  }
  suporteSheet.getRange(suporteSheet.getLastRow() + 1, 1, itens.length, itens[0].length).setValues(itens); //Writes the last iteration as many times as the iterations (18)

This is the log, showing the correct result: enter image description here

This is how this is writing to the spreadsheet: enter image description here

I can't see where the flaw is here, besides my existence.

Thanks for the light!

almost 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Try to change:

itens.push(values);

to:

itens.push(values.slice());

Еxplanation

Log shows you the current state of the array values at every iteration of the loop. During the next iteration, you change the array values. And all 'previous instances' of the array are changing as well. This is why you're getting the 18 identical arrays. Because all of them are 'references' to the same array values.

If you want to prevent the changes in the 'previous instances' you have to make a copy of current state of the array values and put in the itens this copy. The method array.slice() returns a copy of a given array.

almost 3 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda