Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an n-sized Array while making JSLint happy?

JSlint doesn't like the use of Array constructors and there are no JSLint options for allowing them. Therefore, to create an Array of length n, the following is not allowed:

var arr = new Array(n);

Is the below the only way I can get around this?

var arr = [];
arr.length = 5;

In normal circumstances this is not a big deal (using two lines of code instead of one), but I regret not being able to use the concise string multiplier hack:

function repeat(str, times) {
    return new Array(times + 1).join(str);
}
like image 959
Ates Goral Avatar asked Mar 09 '12 03:03

Ates Goral


1 Answers

JSLint is fairly easy to outsmart.

You can just do this:

function repeat(str, times) {
    var A = Array;
    return new A(times + 1).join(str);
}

This would also work:

function repeat(str, times) {
    return new Array.prototype.constructor(times + 1).join(str);
}
like image 158
Dagg Nabbit Avatar answered Oct 31 '22 22:10

Dagg Nabbit