Is there a shortcut to create an array in JavaScript?

I have this javascript:

function padded_array(k, value){ var a = []; a[k] = value; return a; } padded_array(3, "hello"); //=> [undefined, undefined, undefined, 'hello'] 

Is it possible to shorten the code in the function body?

+4
source share
5 answers

for all googlers arriving here - you're probably looking for this:

 var pad_array = function(arr,len,fill) { return arr.concat(Array(len).fill(fill)).slice(0,len); } 
+16
source

If you want to exclude hi, you can use

new Array(count);

to create arrays with arrays.

Edit: Maybe so?

new Array(5).concat("hello")

+4
source

Not in standard ES5 or predecessor. Of course, you can do something like $.extend([], {"3": "hello"}) in jQuery; you can even do

 Object.create(Array.prototype, {"3": {value: "hello"} }); 

in bare ES5, but it's a hack, I would not consider this decision (if everything is ok with you, you can take it).

+1
source

You can use this if your JS does not support Array.prototype.fill() (e.g. Google Apps Script) and you cannot use the code from the first answer:

 function array_pad(array, length, filler) { while(true) if(array.push(filler) >= length) break; return array; } 
+1
source

Another solution using the spread operator:

 padArray = (length, value) => [...Array(length).fill(), value]; 

And the use is the same as you mentioned:

 padded_array(3, "hello"); //=> [undefined, undefined, undefined, 'hello'] 
0
source

Source: https://habr.com/ru/post/1384989/


All Articles