javascriptjqueryunderscore.js

do <something> N times (declarative syntax)


Is there a way in Javascript to write something like this easily:

[1,2,3].times do {
  something();
}

Any library that might support some similar syntax maybe?

Update: to clarify - I would like something() to be called 1,2 and 3 times respectively for each array element iteration


Solution

  • This answer is based on Array.forEach, without any library, just native vanilla.

    To basically call something() 3 times, use:

    [1,2,3].forEach(function(i) {
      something();
    });
    

    considering the following function:

    function something(){ console.log('something') }
    

    The output will be:

    something
    something
    something
    

    To complete this questions, here's a way to do call something() 1, 2 and 3 times respectively:

    It's 2017, you may use ES6:

    [1,2,3].forEach(i => Array(i).fill(i).forEach(_ => {
      something()
    }))
    

    or in good old ES5:

    [1,2,3].forEach(function(i) {
      Array(i).fill(i).forEach(function() {
        something()
      })
    }))
    

    In both cases, the output will be

    The output will be:

    something
    
    something
    something
    
    something
    something
    something
    

    (once, then twice, then 3 times)