Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!weretis.net!feeder4.news.weretis.net!news.teledata-fn.de!newsfeed.arcor.de!newsspool2.arcor-online.net!news.arcor.de.POSTED!not-for-mail Content-Type: text/plain; charset="ISO-8859-1" Message-ID: <2236669.bzG4ezAXRf@PointedEars.de> From: Thomas 'PointedEars' Lahn Reply-To: Thomas 'PointedEars' Lahn Organization: PointedEars Software (PES) Date: Sat, 28 Jan 2012 01:42:42 +0100 User-Agent: KNode/4.4.11 Content-Transfer-Encoding: 7Bit Subject: Re: Initialize multi-dimensional array Newsgroups: comp.lang.javascript References: <81f35d2e-80d0-45aa-965a-c0093cbf4fbf@b23g2000yqn.googlegroups.com> <1934720.aqSPkdTlGX@PointedEars.de> Followup-To: comp.lang.javascript MIME-Version: 1.0 Lines: 69 NNTP-Posting-Date: 28 Jan 2012 01:42:43 CET NNTP-Posting-Host: a21fd9e4.newsspool3.arcor-online.net X-Trace: DXC=FYcmdf35jQg[F<50eo:0knMcF=Q^Z^V3h4Fo<]lROoRa8kFg X-Complaints-To: usenet-abuse@arcor.de Xref: x330-a1.tempe.blueboxinc.net comp.lang.javascript:10661 Thomas 'PointedEars' Lahn wrote: > Andreas Bergmaier wrote: >> var a=[];for(var i=0;i<2;i++){a[i]=[];for(var j=0;j<4;j++)a[i][j]=1;} > ^^ ^^ > JFYI: You are using two Array literals here, of course. > >> There might be tricky expressions with less code, but you don't really >> want them. > > A matter of opinion. Surely > > var a = []; > a.length = 5; > a = a.join("1").split("").map(function (el) { return +el; }); > a = [a, a.slice()]; > > is a more elegant solution to this problem. It should be noted that this approach can also be used with multi-digit numbers and any other value: var a = []; a.length = 5; a = a.join(",12").split(",").map(function (el) { return +el; }); a.shift(); a = [a, a.slice()]; However more elegant, the map() method is not backwards compatible (so it requires comparably expensive emulation) and it is expensive itself because the function needs to be called multiple times. Also, the need for additional shift() (or pop(), if you use "12," instead) with multi-character values reduces its elegance. So a combination of the classical looping approach and the more elegant slicing approach (which performs the element assignment natively, therefore should be cheaper than an explicit loop) appears to be the best solution: function getFilledMatrix(rows, columns, fill) { var a = []; var tmp = []; tmp.length = columns; for (var j = 0; j < columns; ++j) { tmp[j] = fill || 0; } for (var i = 0; i < rows; ++i) { if (i == 0) { a.push(tmp); } else { a.push(tmp.slice()); } } return a; } PointedEars -- When all you know is jQuery, every problem looks $(olvable).