Home > Software engineering >  Variable value is not getting updated after adding an element to the array in apps script(Google She
Variable value is not getting updated after adding an element to the array in apps script(Google She

Time:03-10

This is part of the code.

var newarray = [

["A","B"],

["C","D"]

];

var dimensions = newarray.length;

ss.getRange(15,8).setValue(dimensions);

newarray.push(["Bharat","Lata"])

ss.getRange(18,8).setValue(newarray.length);

ss.getRange(21,8).setValue(dimensions);

Numbers in 15th, 18th, 21st row

I was expecting that dimensions value will be equal to 3 after adding an element to the newarray.

CodePudding user response:

This is happening because you're not updating the variable dimensions after pushing new row in newarray.

Try following modification:

var newarray = [["A","B"],["C","D"]];

var dimensions = newarray.length;

ss.getRange(15,8).setValue(dimensions);

newarray.push(["Bharat","Lata"])
 
dimensions = newarray.length;

ss.getRange(18,8).setValue(newarray.length); // you can use dimensions here too 

ss.getRange(21,8).setValue(dimensions);

CodePudding user response:

You have to update also var dimensions = newarray.length; after updating newarray

function myFunction() {
  var sh = SpreadsheetApp.getActiveSheet()
  var newarray = [
    ["A", "B"],
    ["C", "D"]
  ];
  var dimensions = newarray.length;
  sh.getRange(15, 8).setValue(dimensions);
  newarray.push(["Bharat", "Lata"])
  dimensions = newarray.length;
  sh.getRange(18, 8).setValue(newarray.length);
  sh.getRange(21, 8).setValue(dimensions);
}
  • Related