0

Following this answer for an analogous question for vanilla JavaScript, I've tried to create an array of integers from 1 to 20 with the following code:

var k=Array.from(new Array(20), (x,i) => i + 1);

but I get Syntax error. Evidently Google App Script does not support ES6.

Is there any modern alternative to for ... loop?

tic
  • 3,599
  • 15
  • 39
  • 82

3 Answers3

3
  • You want to create an array including the number in each element using Google Apps Script.
    • It's like [1.0, 2.0, 3.0,,, 20]

If my understanding is correct, how about this workaround? Please think of this as just one of several workarounds. In this workaround, I used Array.apply().

Sample script:

var res = Array.apply(null, Array(20)).map(function(_, i) {return i + 1});
console.log(res); // or for Google Apps Script, Logger.log(res)

Note:

  • For example, when Array.apply(null, Array(3)}) is run, an array of [null, null, null] is created. In this script, values are put in each element using map().
  • Above script can be worked with Google Apps Script.
  • If you want to use Logger.log(), please replace console.log(res) to Logger.log(res).

References:

If this workaround was not the direction you want, I apologize.

Tanaike
  • 139,542
  • 10
  • 71
  • 111
2

Issue:

The main issue is that arrays created using new Array(length) is sparse and have elements that's never set and most array methods don't work on it.

Solution:

It's possible to create a dense array from sparse array using apply. Then, it's easy to get indexes of that array using Object.keys()

Snippets:

//using concat
function test11(){
  Array.prototype.range = function(len){
    return Object.keys(Array.prototype.concat.apply([],new Array(len)))//sparse to dense
  }
  Logger.log([].range(16))
}

//using push
function test12(){
Array.prototype.range = function(len){
  var out = [];
  Array.prototype.push.apply(out,new Array(len))
  return Object.keys(out);
}
Logger.log([].range(15))
}
Community
  • 1
  • 1
TheMaster
  • 37,620
  • 6
  • 43
  • 68
2

No. for/while loop is still best (performant) even on modern browsers. A small function can be used :

function range(n) { var a = []; while(n) a[n - 1] = n--; return a }

console.log( range(5) )
Slai
  • 21,055
  • 5
  • 42
  • 49