0

I'm wondering if there is a way to create javascript/jquery array in one-liner to receive something like:

my_array = ['-', '-', ,'-' ,'-']

Idea is that array should be created with dynamic length and all values filled with given value.

Thanks in advance!

0

2 Answers 2

1

Try:

var total = 4;
var my_array = new Array(total + 1).join("-").split("");

document.write(JSON.stringify(my_array))

.fill Support The native function will be added in (ECMAScript 6), but for now is not available.

if(!Array.prototype.fill){
    Array.prototype.fill = function(val){
        for (var i = 0; i < this.length; i++){
            this[i] = val
        }
        return this
    }
}

var my_array = new Array(4).fill("-"); //returns ["-","-","-","-"]
Sign up to request clarification or add additional context in comments.

2 Comments

This only works if you want to fill the array with a single character string. Try switching "-" to "abc" to see what I mean.
It is why the "downvote" ?. Reason: Question.
0

Try to use:

Array.apply(null, new Array(63)).map(String.prototype.valueOf,"-")

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.