How can I create a two dimensional array in JavaScript?

后端 未结 30 4285
天涯浪人
天涯浪人 2020-11-21 05:25

I have been reading online and some places say it isn\'t possible, some say it is and then give an example and others refute the example, etc.

  1. How do I dec

30条回答
  •  感动是毒
    2020-11-21 05:27

    How to create an empty two dimensional array (one-line)

    Array.from(Array(2), () => new Array(4))
    

    2 and 4 being first and second dimensions respectively.

    We are making use of Array.from, which can take an array-like param and an optional mapping for each of the elements.

    Array.from(arrayLike[, mapFn[, thisArg]])

    var arr = Array.from(Array(2), () => new Array(4));
    arr[0][0] = 'foo';
    console.info(arr);

    The same trick can be used to Create a JavaScript array containing 1...N


    Alternatively (but more inefficient 12% with n = 10,000)

    Array(2).fill(null).map(() => Array(4))
    

    The performance decrease comes with the fact that we have to have the first dimension values initialized to run .map. Remember that Array will not allocate the positions until you order it to through .fill or direct value assignment.

    var arr = Array(2).fill(null).map(() => Array(4));
    arr[0][0] = 'foo';
    console.info(arr);


    Follow up

    Here's a method that appears correct, but has issues.

     Array(2).fill(Array(4)); // BAD! Rows are copied by reference
    

    While it does return the apparently desired two dimensional array ([ [ <4 empty items> ], [ <4 empty items> ] ]), there a catch: first dimension arrays have been copied by reference. That means a arr[0][0] = 'foo' would actually change two rows instead of one.

    var arr = Array(2).fill(Array(4));
    arr[0][0] = 'foo';
    console.info(arr);
    console.info(arr[0][0], arr[1][0]);

提交回复
热议问题