2

Possible Duplicate:
What's wrong with var x = new Array();

if (!Number.prototype.toZeroPaddedString) {
  Number.prototype.toZeroPaddedString = function (count) {
    "use strict";
    var str = this.toString();
    return (new Array(count + 1 - str.length)).join('0') + str;
  };
}

I want my code to be clean by jsLint standards, however, I just cannot imagine how to get rid of this error given what I want to do.

Any advice?

Thanks.

Community
  • 1
  • 1
mark
  • 59,016
  • 79
  • 296
  • 580

2 Answers2

5

The array literal notation is an alternative to using new Array() because Crockford (rightfully) doesn't like the new keyword. The notation is [], just as the literal notation for new Object() is {}. To make it so that the length of the array is as desired, you can set .length on an array.

return (new Array(count + 1 - str.length)).join('0') + str;

To:

var arr = [];
arr.length = count + 1 - str.length;
return arr​.join('0') + str;
jeremy
  • 9,965
  • 4
  • 39
  • 59
  • 2
    I may be dead wrong, but I believe `new Array(someNumber)` is different from `new Array(elem1, elem2, ...)` in that it creates an array of *length* `someNumber` with undefined elements. –  Sep 02 '12 at 03:27
  • `new Array(2) === [undefined, undefined]` whereas `[2]` is just `[2]`. Your answer seems to be simply misleading. – mark Sep 02 '12 at 03:28
  • Sorry for the confusion @delnan, I've updated my post, Mark. – jeremy Sep 02 '12 at 03:34
  • Now that's what I call misuse of the comma operator. Why not split that up in separate statements? Also, you're missing a `var`, your version makes `arr` global. –  Sep 02 '12 at 03:38
  • @delnan I've updated again. Setting `var` wasn't working as I expected, so I set it as a global. – jeremy Sep 02 '12 at 03:40
0

Try this:

if (!Number.prototype.toZeroPaddedString) {
  Number.prototype.toZeroPaddedString = function (count) {
    "use strict";
    var str = this.toString();
    var ary = [];
    ary.length = count + 1 - str.length;
    return ary.join('0') + str;
  };
}
Russ
  • 1,931
  • 1
  • 14
  • 15