# ES6 solution:

``````[...new Array(5)].map(x => 0); // [0, 0, 0, 0, 0]
``````

# 用預先計算的值填充數組的優雅方式

``````> Array.from(Array(3), () => 0)
< [0, 0, 0]
``````

``````> Array.from(Array(10), () => Math.floor(10 * Math.random()))
< [3, 6, 8, 1, 9, 3, 0, 6, 7, 1]
``````

``````const numbers = Array(10);
for (let i = 0; i < numbers.length; i++) {
numbers[i] = Math.round(10 * Math.random());
}
``````

``````> Array.from(Array(10), (d, i) => i)
< [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
``````

# 獎勵答案：使用String `repeat()`填充數組

``````> "?".repeat(10).split("").map(() => Math.floor(10 * Math.random()))
< [5, 6, 3, 5, 0, 8, 2, 7, 4, 1]
``````

``````> "?".repeat(10)
< "??????????"

> "?".repeat(10).split("")
< ["?", "?", "?", "?", "?", "?", "?", "?", "?", "?"]

> "?".repeat(10).split("").map(() => Math.floor(10 * Math.random()))
< [5, 6, 3, 5, 0, 8, 2, 7, 4, 1]
``````

2013年8月更新，2015年2月更新：2009年以下的答案與JavaScript的通用`Array`類型有關。 它不涉及ES2015中定義的新類型數組[現在可在許多瀏覽器中使用]，如`Int32Array`等。 另請注意，ES2015為Arrays類型數組添加了`fill`方法，這可能是填充它們的最有效方法。

``````function newFilledArray(len, val) {
var rv = new Array(len);
while (--len >= 0) {
rv[len] = val;
}
return rv;
}
``````

``````<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<title>Zero Init Test Page</title>
<style type='text/css'>
body {
font-family:    sans-serif;
}
#log p {
margin:     0;
}
.error {
color:      red;
}
.winner {
color:      green;
font-weight:    bold;
}
</style>
<script type='text/javascript' src='prototype-1.6.0.3.js'></script>
<script type='text/javascript'>
var testdefs = {
'downpre':  {
total:  0,
desc:   "Count down, pre-decrement",
func:   makeWithCountDownPre
},
'downpost': {
total:  0,
desc:   "Count down, post-decrement",
func:   makeWithCountDownPost
},
'up':       {
total:  0,
desc:   "Count up (normal)",
func:   makeWithCountUp
},
'downandup':  {
total:  0,
desc:   "Count down (for loop) and up (for filling)",
func:   makeWithCountDownArrayUp
},
'concat':   {
total:  0,
desc:   "Concat",
func:   makeWithConcat
}
};

var markup, defname;

markup = "";
for (defname in testdefs) {
markup +=
"<div><input type='checkbox' id='chk_" + defname + "' checked>" +
"<label for='chk_" + defname + "'>" + testdefs[defname].desc + "</label></div>";
}
\$('checkboxes').update(markup);
\$('btnTest').observe('click', btnTestClick);
});

function epoch() {
return (new Date()).getTime();
}

function btnTestClick() {

// Clear log
\$('log').update('Testing...');

// Show running
\$('btnTest').disabled = true;

// Run after a pause while the browser updates display
btnTestClickPart2.defer();
}
function btnTestClickPart2() {

try {
runTests();
}
catch (e) {
log("Exception: " + e);
}

// Re-enable the button; we don't yheidl
\$('btnTest').disabled = false;
}

function runTests() {
var start, time, counter, length, defname, def, results, a, invalid, lowest, s;

// Get loops and length
s = \$F('txtLoops');
runcount = parseInt(s);
if (isNaN(runcount) || runcount <= 0) {
log("Invalid loops value '" + s + "'");
return;
}
s = \$F('txtLength');
length = parseInt(s);
if (isNaN(length) || length <= 0) {
log("Invalid length value '" + s + "'");
return;
}

// Clear log
\$('log').update('');

// Do it
for (counter = 0; counter <= runcount; ++counter) {

for (defname in testdefs) {
def = testdefs[defname];
if (\$('chk_' + defname).checked) {
start = epoch();
a = def.func(length);
time = epoch() - start;
if (counter == 0) {
// Don't count (warm up), but do check the algorithm works
invalid = validateResult(a, length);
if (invalid) {
log("<span class='error'>FAILURE</span> with def " + defname + ": " + invalid);
return;
}
}
else {
// Count this one
log("#" + counter + ": " + def.desc + ": " + time + "ms");
def.total += time;
}
}
}
}

for (defname in testdefs) {
def = testdefs[defname];
if (\$('chk_' + defname).checked) {
def.avg = def.total / runcount;
if (typeof lowest != 'number' || lowest > def.avg) {
lowest = def.avg;
}
}
}

results =
"<p>Results:" +
"<br>Length: " + length +
"<br>Loops: " + runcount +
"</p>";
for (defname in testdefs) {
def = testdefs[defname];
if (\$('chk_' + defname).checked) {
results += "<p" + (lowest == def.avg ? " class='winner'" : "") + ">" + def.desc + ", average time: " + def.avg + "ms</p>";
}
}
results += "<hr>";
\$('log').insert({top: results});
}

function validateResult(a, length) {
var n;

if (a.length != length) {
return "Length is wrong";
}
for (n = length - 1; n >= 0; --n) {
if (a[n] != 0) {
return "Index " + n + " is not zero";
}
}
return undefined;
}

function makeWithCountDownPre(len) {
var a;

a = new Array(len);
while (--len >= 0) {
a[len] = 0;
}
return a;
}

function makeWithCountDownPost(len) {
var a;

a = new Array(len);
while (len-- > 0) {
a[len] = 0;
}
return a;
}

function makeWithCountUp(len) {
var a, i;

a = new Array(len);
for (i = 0; i < len; ++i) {
a[i] = 0;
}
return a;
}

function makeWithCountDownArrayUp(len) {
var a, i;

a = new Array(len);
i = 0;
while (--len >= 0) {
a[i++] = 0;
}
return a;
}

function makeWithConcat(len) {
var a, rem, currlen;

if (len == 0) {
return [];
}
a = [0];
currlen = 1;
while (currlen < len) {
rem = len - currlen;
if (rem < currlen) {
a = a.concat(a.slice(0, rem));
}
else {
a = a.concat(a);
}
currlen = a.length;
}
return a;
}

function log(msg) {
\$('log').appendChild(new Element('p').update(msg));
}
</script>
<body><div>
<label for='txtLength'>Length:</label><input type='text' id='txtLength' value='10000'>
<br><label for='txtLoops'>Loops:</label><input type='text' id='txtLoops' value='10'>
<div id='checkboxes'></div>
<br><input type='button' id='btnTest' value='Test'>
<hr>
<div id='log'></div>
</div></body>
</html>
``````

ECMAScript2016 ，大數組就有一個明確的選擇。

``````const arr = [];
arr.length = 120000;
let i = 0;
while (i < 120000) {
arr[i] = 0;
i++;
}``````

``````(arr = []).length = n;
let i = 0;
while (i < n) {
arr[i] = 0;
i++;
}
``````

``````const arr = Array(n).fill(0);
``````

I just use :

``````var arr = [10];
for (var i=0; i<=arr.length;arr[i] = i, i++);
``````

It might be worth pointing out, that `Array.prototype.fill` had been added as part of the ECMAScript 6 (Harmony) proposal . I would rather go with the polyfill written below, before considering other options mentioned on the thread.

``````if (!Array.prototype.fill) {
Array.prototype.fill = function(value) {

// Steps 1-2.
if (this == null) {
throw new TypeError('this is null or not defined');
}

var O = Object(this);

// Steps 3-5.
var len = O.length >>> 0;

// Steps 6-7.
var start = arguments[1];
var relativeStart = start >> 0;

// Step 8.
var k = relativeStart < 0 ?
Math.max(len + relativeStart, 0) :
Math.min(relativeStart, len);

// Steps 9-10.
var end = arguments[2];
var relativeEnd = end === undefined ?
len : end >> 0;

// Step 11.
var final = relativeEnd < 0 ?
Math.max(len + relativeEnd, 0) :
Math.min(relativeEnd, len);

// Step 12.
while (k < final) {
O[k] = value;
k++;
}

// Step 13.
return O;
};
}
``````

The fastest way to do that is with forEach =)

(we keep backward compatibility for IE < 9)

``````var fillArray = Array.prototype.forEach
? function(arr, n) {
arr.forEach(function(_, index) { arr[index] = n; });
return arr;
}
: function(arr, n) {
var len = arr.length;
arr.length = 0;
while(len--) arr.push(n);
return arr;
};

// test
fillArray([1,2,3], 'X'); // => ['X', 'X', 'X']
``````

There's always the phpjs solution, which you can find here:

I can't speak for the project (creating a library of javascript functions that mirrors the greater functionality of php) as a whole, but the few functions that I've personally pulled from there have worked like a champ.

``````var x = [];
``````

``````var x = [0,0,0,0,0,0];
``````

``````var x = new Array(7);
``````

``````var x = [];
for (var i = 0; i < 10; i++) x[i] = 0;
``````

``````var x = new Array();
``````

``````var y = [];
``````

``````function filledArray(len, value) {
if (len <= 0) return [];
var result = [value];
while (result.length < len/2) {
result = result.concat(result);
}
return result.concat(result.slice(0, len-result.length));
}
``````

``````function filledArrayString(len, value) {
return new Array(len+1).join(value).split('');
}
``````

``````var zero = newFilledArray(maxLength, 0);
``````

``````zero.slice(0, requiredLength);
``````

``````a = new Array(10).fill(0);
``````

``````function makeRec(len, acc) {
if (acc == null) acc = [];
if (len <= 1) return acc;
var b = makeRec(len >> 1, [0]);
b = b.concat(b);
if (len & 1) b = b.concat([0]);
return b;
},
``````

``````Array.apply(null, Array(5)).map(Number.prototype.valueOf,0);
new Array(5+1).join('0').split('').map(parseFloat);
``````

`new Array(3).fill(0)`會給你`[0, 0, 0]` 。 您可以使用任何值填充數組，例如`new Array(5).fill('abc')` （即使是對象和其他數組）。

``````arr = [1, 2, 3, 4, 5, 6]
arr.fill(9, 3, 5)  # what to fill, start, end
``````

``````Array.prototype.init = function(x,n)
{
if(typeof(n)=='undefined') { n = this.length; }
while (n--) { this[n] = x; }
return this;
}

var a = (new Array(5)).init(0);

var b = [].init(0,4);
``````

``````//my original method
Array.prototype.init = function(x,n)
{
if(typeof(n)=='undefined') { n = this.length; }
while (n--) { this[n] = x; }
return this;
}

//now using push which I had previously thought to be slower than direct assignment
Array.prototype.init2 = function(x,n)
{
if(typeof(n)=='undefined') { n = this.length; }
while (n--) { this.push(x); }
return this;
}

//joshua's method
function newFilledArray(len, val) {
var a = [];
while(len--){
a.push(val);
}
return a;
}

//test m1 and m2 with short arrays many times 10K * 10

var a = new Date();
for(var i=0; i<10000; i++)
{
var t1 = [].init(0,10);
}
var A = new Date();

var b = new Date();
for(var i=0; i<10000; i++)
{
var t2 = [].init2(0,10);
}
var B = new Date();

//test m1 and m2 with long array created once 100K

var c = new Date();
var t3 = [].init(0,100000);
var C = new Date();

var d = new Date();
var t4 = [].init2(0,100000);
var D = new Date();

//test m3 with short array many times 10K * 10

var e = new Date();
for(var i=0; i<10000; i++)
{
var t5 = newFilledArray(10,0);
}
var E = new Date();

//test m3 with long array created once 100K

var f = new Date();
var t6 = newFilledArray(100000, 0)
var F = new Date();
``````

``````IE7 deltas:
dA=156
dB=359
dC=125
dD=375
dE=468
dF=412

FF3.5 deltas:
dA=6
dB=13
dC=63
dD=8
dE=12
dF=8
``````

So by my reckoning push is indeed slower generally but performs better with longer arrays in FF but worse in IE which just sucks in general (quel surprise).

``````  var zeroFilled = [].slice.apply(new Uint8Array(1000000))
``````

``````  var zeroFilled = [].slice.apply(new Uint8Array(new Array(1000000))
``````

Chrome 25.0.1364.160

1. 弗雷德里克戈特利布 - 6.43
2. 薩姆巴納姆 - 4.83
3. Eli - 3.68
4. 約書亞2.91
5. Mathew Crumley - 2.67
6. bduran - 2.55
7. 艾倫賴斯 - 2.11
8. kangax - 0.68
9. TJ。 Crowder - 0.67
10. zertosh - 錯誤

Firefox 20.0

1. 艾倫賴斯 - 1.85
2. 約書亞 - 1.82
3. Mathew Crumley - 1.79
4. bduran - 1.37
5. 弗雷德里克戈特利布 - 0.67
6. 薩姆巴納姆 - 0.63
7. Eli - 0.59
8. kagax - 0.13
9. TJ。 Crowder - 0.13
10. zertosh - 錯誤

``````Array.apply(null, Array(5)).map(Number.prototype.valueOf,0);
// [0, 0, 0, 0, 0]
``````

``````Array.apply(null, Array(3)).map(String.prototype.valueOf,"hi")
// ["hi", "hi", "hi"]
``````

``````new Array(5+1).join('0').split('')
// ["0", "0", "0", "0", "0"]
``````

``````new Array(5+1).join('0').split('').map(parseFloat)
// [0, 0, 0, 0, 0]
``````

``````function makeArrayOf(value, length) {
var arr = [], i = length;
while (i--) {
arr[i] = value;
}
return arr;
}

makeArrayOf(0, 5); // [0, 0, 0, 0, 0]

makeArrayOf('x', 3); // ['x', 'x', 'x']
``````

``````function zeroFilledArray(size) {
return new Array(size + 1).join('0').split('');
}
``````