wolfblitzer wolfblitzer - 1 year ago 78
Javascript Question

Doing math on a for loop variable in Google Scripts

I have two for loops that I'm going through:
The first is creating an array called valuesDeletion that puts the row number in position [i] unless a condition is met, in which case it puts 'y'.
The second one is checking valuesDeletion for any 'y' and deleting that row.
The problem is, the rows I should be deleting are actually j+1 due to the way ranges are set up and stuff, but I can't seem to do math on the variable j.

I've tried:

  • parseInt(j)+1

  • +j + 1

  • +j + +1

  • parseFloat(j) + 1

  • etc...

Everything I do just concats the two together giving me things like 11 instead of 2 and 111 instead of 12. It seems like I have something fundamentally wrong with my logic I guess. I'm new to javascript as a whole- so if more context is needed (aka the rest of my code) just let me know and I'll be happy to provide.

for ( var i = 0; i < lastRow; i++ ) {
valuesDeletion[i] = i;
if ( valuesMaster[i][getColIndexByName('Updated')] < incrementDate(today,-30) && valuesMaster[i][getColIndexByName('Status')] == "Live" ) {

valuesDeletion[i] = 'y';

for ( var j = lastRow; j >= 0; j-- ) {
if ( valuesDeletion[j] == 'y' ) {
Logger.log('j: '+ j + 1);
// s.deleteRow(j);

Answer Source

'j: '+ j is a string. When you add 1 to that string, you end up doing string concatenation.

You need to use parentheses to perform the addition first:

'j: '+ (j + 1)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download