I try to create a dynamic 2 dimensional array using the prototype.slice.call. The array dimension varies depending on the value k inserted by the user. The code is as follows:
var A = new Array(k);
if (k > 1) {
var args = Array.prototype.slice.call(k, 1);
for (var n = 0; n < k; n++) {
A[n] = new Array.apply(this, args);
}
}
alert (A);
.slice()is the wrong tool. It’s used for making a shallow clone of another Array, or part of the Array.If you’re looking for a square structure, you’d just use 2 nested loops to create the outer and inner arrays.
http://jsfiddle.net/zGhnv/
Notice that I really don’t need to declare the initial length of the Array. I can just add members to each array as needed.
If you want to declare the length up front, you could replace both
[]withnew Array(k).