Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating array of empty strings?

Tags:

Is there an easy way to create an array of empty strings in javascript? Currently the only way I can think to do it is with a loop:

var empty = new Array(someLength); for(var i=0;i<empty.length;i++){     empty[i] = ''; } 

but I'm wondering if there is some way to do this in one line using either regular javascript or coffeescript.

like image 807
Abe Miessler Avatar asked Nov 15 '13 17:11

Abe Miessler


People also ask

How do you create an empty array of strings?

You can initialize an empty string array as const arr: string[] = [] . The array can contain zero or more elements of type string .

How do you create an empty string array in Java?

However, there's one nice thing about arrays - their size can't change, so you can always use the same empty array reference. So in your code, you can use: private static final String[] EMPTY_ARRAY = new String[0];

How do you create an empty array?

1) Assigning it to a new empty array This is the fastest way to empty an array: a = []; This code assigned the array a to a new empty array. It works perfectly if you do not have any references to the original array.

How do you create an empty string array in Python?

Python numpy empty string array To create an empty array of strings we can easily use the function np. empty(). To create an empty array of 4 strings (with size 3), we need to pass 'S3' as a dtype argument in the np. empty() function.


2 Answers

Update: on newer browsers - use .fill: Array(1000).fill('') will create an array of 1000 empty strings.


Yes, there is a way:

 var n = 1000;  Array(n).join(".").split("."); // now contains n empty strings. 

I'd probably use the loop though, it conveys intent clearer.

function repeat(num,whatTo){     var arr = [];     for(var i=0;i<num;i++){         arr.push(whatTo);     }     return arr; } 

That way, it's perfectly clear what's being done and you can reuse it.

like image 110
Benjamin Gruenbaum Avatar answered Oct 19 '22 23:10

Benjamin Gruenbaum


You can get an array defining the size and fill it with some tokens:

const arr = Array(size).fill(""); 
like image 22
user2592256 Avatar answered Oct 20 '22 00:10

user2592256