Idiom for “repeat n times”?

后端 未结 6 2193
忘掉有多难
忘掉有多难 2020-12-15 02:24

EDIT: The votes to close are wrong. The accepted answer in Repeat Character N Times is not applicable in general. E.g.:

>>>         


        
6条回答
  •  甜味超标
    2020-12-15 03:12

    Maybe the Array.from callback can be of use:

    var result = Array.from(Array(3), Math.random);
    
    console.log(result);

    There is a slight advantage here over using map: map already needs an array with all the entries (maybe created with fill or the spread syntax), to then create the final array from that. So in total a map solution will create n entries twice. Array.from does not need an array with entries, just an object with a length property will do, and Array(3) is providing that.

    So depending on your preferences, the above can also be done like this:

    var result = Array.from({length:3}, Math.random);
    
    console.log(result);

    Finally, if you would create a repeat function for this, you can name the argument length and use the ES6 short notation for object literals:

    const repeat = (length, cb) => Array.from({length}, cb);
    
    const result = repeat(3, Math.random);
    console.log(result);

提交回复
热议问题