0

I need javasctript function that writes number of 1 together witch depends on value counter. So if is counter 6 write number 1 six time together.

Here is example output what i need:

 var counter = 6;

 var output = "111111";

I search forum here...but i have not found any solution how to make this.Any help is welcomed.

2
  • you are going to need a for loop Commented Jan 12, 2014 at 22:38
  • Seems like you didn't even try ... shame ... Commented Jan 12, 2014 at 22:44

4 Answers 4

3

Here you have a one-liner

var output = Array(counter + 1).join("1");   //"111" for counter = 3

Cheers

Sign up to request clarification or add additional context in comments.

1 Comment

thank You...this is the shortes code as possible...so here is complete code that contains Your solution. If someoneneeds it here is it. Thank You.
2

Here is a function that does what you want:

function repeat(letter, count) {
  var answer = '';

  while(count--) {
    answer += letter;
  }

  return answer;
}

// usage:
var onesixtimes = repeat('1', 6); // '111111'

Comments

1

EDIT:

Completely forgot that ES6 will also have a String.prototype.repeat method:

var s = "1".repeat(6);

This is available right now in Firefox, but a patch is needed for older browsers.


Original answer:

ECMAScript 6 will have a Array.prototype.fill method.

var s = Array(6).fill("1").join("");

You can use it now with a compatibility patch.

Something like this should be close, though perhaps not entirely compatible:

if (!Array.prototype.fill) {
    Array.prototype.fill = function(val, start, end) {
        start = parseInt(start)
        start = isNaN(start) ? 0 :
                start < 0    ? Math.max(this.length + start, 0) :
                               Math.min(this.length, start)

        end = parseInt(end)
        end = isNaN(end) ? this.length :
              end < 0    ? Math.max(this.length + end, 0) :
                           Math.min(this.length, end)

        while (start < end)
            this[start++] = val

        return this
    }
}

2 Comments

Don't forget to join afterwarsd to turn it into the string the OP expects.
@Tibos: Thanks, forgot about that.
0

Here is a fiddle that shows it working

function writeNum(counter, integer){
    var arr = [];
    for (var i = 0; i < counter; i++){
        arr.push(integer);
    }
    return arr.join("");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.