Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
55
rated 0 times [  57] [ 2]  / answers: 1 / hits: 120248  / 14 Years ago, fri, october 29, 2010, 12:00:00

Is there a more compact way to do this sort of initialization?



for (var i = 0; i < arraySize; i++) array[i] = value;

More From » javascript

 Answers
38
while(arraySize--) array.push(value);


no initialization (that i know of)






Update



Since ever posting this answer 4 years ago, people seem to keep coming back here for this answer. For benchmarking purposes I made a JSPerf with some different solutions.



The solution above here isn't the quickest, although it's short. To stick to the same short style, but with a better performance:



while(size--) array[size] = value;





Update Feb 2016
Updated the JSPerf with a new revision with more testcases.



If performance doesn't matter and you want a one-liner:



var value = 1234, // can be replaced by a fixed value
size = 1000, // can be replaced by a fixed value
array = Array.apply(null,{length: size}).map(function() { return value; });


A more performant solution (in one, dirty, line):
Be aware: this replaces existsing value, size and i variables in the scope



for(var i = 0, value = 1234, size = 1000, array = new Array(1000); i < size; i++) array[i] = value;

[#95144] Tuesday, October 26, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
claudia

Total Points: 734
Total Questions: 106
Total Answers: 113

Location: Sweden
Member since Fri, Apr 16, 2021
3 Years ago
;