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!

doctore
  • 146
  • 5

2 Answers2

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 ["-","-","-","-"]
0

Try to use:

Array.apply(null, new Array(63)).map(String.prototype.valueOf,"-")
suvroc
  • 3,058
  • 1
  • 15
  • 29