1

How do you write a function given arguments width, height and value that make a two dimensional array with that given width and height and fill every spot with a given value?

function createGrid(width, height, value) {
    var array = new Array(height);

    for (var i = 0; i < height; i++) {
        array[i] = new Array(width);
    }

    for (var j = 0; j < width; j++) {
        for (var k = 0; k < height; k++) {
            array[k][j] = value;
        }
    }
    return array;
}

This is what I wrote, but I'm wondering why I can't just write something like var array = new array(width, height). Why isn't such simple syntax possible in Javascript?

3
  • 1
    Because that's how it was designed. Commented Dec 20, 2015 at 19:10
  • Is this possible in other languages? Who do you think they would opt for such an odd design though? Commented Dec 20, 2015 at 19:12
  • 1
    In JS this not possible mainly because JS doesn't have multidimensional arrays. You can emulate them with nested arrays though. Commented Dec 20, 2015 at 19:23

1 Answer 1

1

I would use a function like this:

function createGrid(width, height, value) {
    return Array.apply(null, { length: height }).map(function () {
        return Array.apply(null, { length: width }).map(function () {
            return value;
        });
    });
}

document.write('<pre>' + JSON.stringify(createGrid(5, 4, 42), 0, 4) + '</pre>');

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.