Reputation: 353
I am building Tetris. I have figured out how to build a HTML table out of a two-dimensional array. However, normal Tetris is played in a ten-by-twenty grid. I am having troubles creating the inner arrays. I looked at this question, but all of the answers don't make sense to me, are based around jQuery, or I can't tell the difference. The code doesn't result in an error. It outputs an empty array, when it should output a length-three array. (This is to test the code.) Can someone tell me what I'm doing wrong?
function array(x, text) {
var toBuild = [];
for (var i; i < x-1; i++) {toBuild.push(text); }
console.log(toBuild);
return toBuild;
}
console.log(array(3, "hello"));
Upvotes: 1
Views: 37
Reputation: 36564
The reason is you are not initializing the i
in your for loop. You should assign it to 0
.
If you want your code to output an array o length 10
then you should pass 10
to your function and there is not to use x-1
. You should use x
function array(x, text) {
var toBuild = [];
for (var i = 0; i < x; i++) {toBuild.push(text); }
console.log(toBuild);
return toBuild;
}
console.log(array(10, "hello"));
The more fancy way of doing the same this is to use fill
const array = (x, text) => Array(x).fill(text)
console.log(array(10, "hello"));
Upvotes: 2