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).