1

I want to type something like [1] * totalPoints so that if totalPoints was 3, it would give me an array of [1,1,1]. I can't think of what it would be called though.. as such, my searches have turned up nothing. I mean, I could easily accomplish this with a for loop, but I seem to be under the impression that I've used something like this before and I just can't think of it. Is there anything like this in javascript?

4

2 Answers 2

2

Create a new array of size 3 then use the array map function on each element, calling valueOf:

var totalPoints = Array.apply(null, new Array(3)).map(Number.prototype.valueOf,1);

http://jsfiddle.net/pXgu4/

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

7 Comments

This is the closest to what I was looking for. totalPoints was the variable however, so it would go where the 3 is and the array would be named something else. Thanks for your answer. ^^
Though this is nifty code, I would recommend against it. Really what's the reason to save those few lines of a loop but in return making a task as simple as this look so complicated? Anyone looking at this code will have trouble understanding what it does, including you in a few weeks (if you even understand how this works in the first place). Readability is more important than saving yourself a couple of lines.
@IngoBürk and is the slowest option. A pre-allocated array filled with a for-loop is by far the fastest option (jsperf.com/pre-fill-an-array)
@Ken But that also doesn't matter. If you have to worry about the performance of creating an array with a few entries, you are in a lot of trouble.
@IngoBürk: That all depends on context. Try playing with canvas for example. Every bit counts.
|
0
var myArray = [];

function pointsArray(totalPoints) {
    for (i = 0; i < totalPoints; i++) {
        myArray.push(1);
    }

    return myArray;
}

http://jsfiddle.net/isherwood/CvscV

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.