开发者

How to create multidimensional array

Can anyone give me a sample/example of JavaScript with a multidimensional array of inputs? Hope you could help because I'm s开发者_JS百科till new to the JavaScript.

Like when you input 2 rows and 2 columns the output of it will be 2 rows of input and 2 columns of input.

Like this:

[input][input]                
[input][input]


var numeric = [
    ['input1','input2'],
    ['input3','input4']
];
numeric[0][0] == 'input1';
numeric[0][1] == 'input2';
numeric[1][0] == 'input3';
numeric[1][1] == 'input4';

var obj = {
    'row1' : {
        'key1' : 'input1',
        'key2' : 'input2'
    },
    'row2' : {
        'key3' : 'input3',
        'key4' : 'input4'
    }
};
obj.row1.key1 == 'input1';
obj.row1.key2 == 'input2';
obj.row2.key1 == 'input3';
obj.row2.key2 == 'input4';

var mixed = {
    'row1' : ['input1', 'inpu2'],
    'row2' : ['input3', 'input4']
};
mixed.row1[0] == 'input1';
mixed.row1[1] == 'input2';
mixed.row2[0] == 'input3';
mixed.row2[1] == 'input4';

http://jsfiddle.net/z4Un3/

And if you're wanting to store DOM elements:

var inputs = [
    [
        document.createElement('input'),
        document.createElement('input')
    ],
    [
        document.createElement('input'),
        document.createElement('input')
    ]
];
inputs[0][0].id = 'input1';
inputs[0][1].id = 'input2';
inputs[1][0].id = 'input3';
inputs[1][1].id = 'input4';

Not real sure how useful the above is until you attach the elements. The below may be more what you're looking for:

<input text="text" id="input5"/>
<input text="text" id="input6"/>
<input text="text" id="input7"/>
<input text="text" id="input8"/>    
var els = [
    [
        document.getElementById('input5'),
        document.getElementById('input6')
    ],
    [
        document.getElementById('input7'),
        document.getElementById('input8')
    ]
];    
els[0][0].id = 'input5';
els[0][1].id = 'input6';
els[1][0].id = 'input7';
els[1][1].id = 'input8';

http://jsfiddle.net/z4Un3/3/

Or, maybe this:

<input text="text" value="4" id="input5"/>
<input text="text" value="4" id="input6"/>
<br/>
<input text="text" value="2" id="input7"/>
<input text="text" value="4" id="input8"/>

var els = [
    [
        document.getElementById('input5'),
        document.getElementById('input6')
    ],
    [
        document.getElementById('input7'),
        document.getElementById('input8')
    ]
];

var result = [];

for (var i = 0; i < els.length; i++) {
    result[result.length] = els[0][i].value - els[1][i].value;
}

Which gives:

[2, 0]

In the console. If you want to output that to text, you can result.join(' ');, which would give you 2 0.

http://jsfiddle.net/z4Un3/6/

EDIT

And a working demonstration:

<input text="text" value="4" id="input5"/>
<input text="text" value="4" id="input6"/>
<br/>
<input text="text" value="2" id="input7"/>
<input text="text" value="4" id="input8"/>
<br/>
<input type="button" value="Add" onclick="add()"/>

// This would just go in a script block in the head
function add() {
    var els = [
        [
            document.getElementById('input5'),
            document.getElementById('input6')
        ],
        [
            document.getElementById('input7'),
            document.getElementById('input8')
        ]
    ];

    var result = [];

    for (var i = 0; i < els.length; i++) {
        result[result.length] = parseInt(els[0][i].value) - parseInt(els[1][i].value);
    }

    alert(result.join(' '));
}

http://jsfiddle.net/z4Un3/8/


Quote taken from Data Structures and Algorithms with JavaScript

The Good Parts (O’Reilly, p. 64). Crockford extends the JavaScript array object with a function that sets the number of rows and columns and sets each value to a value passed to the function. Here is his definition:

Array.matrix = function(numrows, numcols, initial) {
    var arr = [];
    for (var i = 0; i < numrows; ++i) {
        var columns = [];
        for (var j = 0; j < numcols; ++j) {
            columns[j] = initial;
        }
        arr[i] = columns;
    }
    return arr;
}

Here is some code to test the definition:

var nums = Array.matrix(5,5,0);
print(nums[1][1]); // displays 0
var names = Array.matrix(3,3,"");
names[1][2] = "Joe";
print(names[1][2]); // display "Joe"

We can also create a two-dimensional array and initialize it to a set of values in one line:

var grades = [[89, 77, 78],[76, 82, 81],[91, 94, 89]];
print(grades[2][2]); // displays 89


Declared without value assignment.

2 dimensions...

var arrayName = new Array(new Array());

3 dimensions...

var arrayName = new Array(new Array(new Array()));


I know this is ancient but what about...

4x4 example (actually 4x<anything>):

var matrix = [ [],[],[],[] ]

which can filled by:

for (var i=0; i<4; i++) {
   for (var j=0; j<4; j++) {
      matrix[i][j] = i*j;
   }
}


Hope the following code suits your requirement

var row= 20;
var column= 10;
var f = new Array();

for (i=0;i<row;i++) {
 f[i]=new Array();
 for (j=0;j<column;j++) {
  f[i][j]=0;
 }
}


function Array2D(x, y)
{
    var array2D = new Array(x);

    for(var i = 0; i < array2D.length; i++)
    {
        array2D[i] = new Array(y);
    }

    return array2D;
}

var myNewArray = Array2D(4, 9);

myNewArray[3][5] = "booger";


very simple

var states = [,];
states[0,0] = tName; 
states[0,1] = '1';
states[1,0] = tName; 
states[2,1] = '1';

. . .

states[n,0] = tName; 
states[n,1] = '1';


var size = 0;   
 var darray = new Array();
    function createTable(){
        darray[size] = new Array();
        darray[size][0] = $("#chqdate").val();
        darray[size][1]= $("#chqNo").val();
        darray[size][2] = $("#chqNarration").val() ;
        darray[size][3]= $("#chqAmount").val();
        darray[size][4]= $("#chqMode").val();
    }

increase size var after your function.


So here's my solution.

A simple example for a 3x3 Array. You can keep chaining this to go deeper

Array(3).fill().map(a => Array(3))

Or the following function will generate any level deep you like

f = arr => {
    let str = 'return ', l = arr.length;
    arr.forEach((v, i) => {
        str += i < l-1 ? `Array(${v}).fill().map(a => ` : `Array(${v}` + ')'.repeat(l);
    });
    return Function(str)();
}
f([4,5,6]) // Generates a 4x5x6 Array

http://www.binaryoverdose.com/2017/02/07/Generating-Multidimensional-Arrays-in-JavaScript/


you can create array follow the code below:

var arraymultidimensional = []
    arraymultidimensional = [[value1,value2],[value3,value4],[value5,value6]];

Result:
[v1][v2] position 0
[v3][v4] position 1
[v5][v6] position 2

For add to array dinamically, use the method below:

//vectorvalue format = "[value,value,...]"
function addToArray(vectorvalue){
  arraymultidimensional[arraymultidimensional.length] = vectorvalue;
}

Hope this helps. :)


I've created an npm module to do this with some added flexibility:

// create a 3x3 array
var twodimensional = new MultiDimensional([3, 3])

// create a 3x3x4 array
var threedimensional = new MultiDimensional([3, 3, 4])

// create a 4x3x4x2 array
var fourdimensional = new MultiDimensional([4, 3, 4, 2])

// etc...

You can also initialize the positions with any value:

// create a 3x4 array with all positions set to 0
var twodimensional = new MultiDimensional([3, 4], 0)

// create a 3x3x4 array with all positions set to 'Default String'
var threedimensionalAsStrings = new MultiDimensional([3, 3, 4], 'Default String')

Or more advanced:

// create a 3x3x4 array with all positions set to a unique self-aware objects.
var threedimensional = new MultiDimensional([3, 3, 4], function(position, multidimensional) {
    return {
        mydescription: 'I am a cell at position ' + position.join(),
        myposition: position,
        myparent: multidimensional
    }
})

Get and set values at positions:

// get value
threedimensional.position([2, 2, 2])

// set value
threedimensional.position([2, 2, 2], 'New Value')


Create uninitialized multidimensional array:

function MultiArray(a) {
  if (a.length < 1) throw "Invalid array dimension";
  if (a.length == 1) return Array(a[0]);
  return [...Array(a[0])].map(() => MultiArray(a.slice(1)));
}

Create initialized multidimensional array:

function MultiArrayInit(a, init) {
  if (a.length < 1) throw "Invalid array dimension";
  if (a.length == 1) return Array(a[0]).fill(init);
  return [...Array(a[0])].map(() => MultiArrayInit(a.slice(1), init));
}

Usage:

MultiArray([3,4,5]);  // -> Creates an array of [3][4][5] of empty cells

MultiArrayInit([3,4,5], 1);  // -> Creates an array of [3][4][5] of 1s


I came up with

let rows = 5;
let cols = 4;
let defaultValue = 0;

Array(rows).fill([]).map((x) => x = Array(cols).fill(defaultValue));

resulting into

(5) [Array(4), Array(4), Array(4), Array(4), Array(4)]
0: (4) [0, 0, 0, 0]
1: (4) [0, 0, 0, 0]
2: (4) [0, 0, 0, 0]
3: (4) [0, 0, 0, 0]
4: (4) [0, 0, 0, 0]
length: 5


I've written a one linear for this:

[1, 3, 1, 4, 1].reduceRight((x, y) => new Array(y).fill().map(() => JSON.parse(JSON.stringify(x))), 0);

I feel however I can spend more time to make a JSON.parse(JSON.stringify())-free version which is used for cloning here.

Btw, have a look at my another answer here.


I know this is an old question but here is something to try: Make your multidimensional array, and place it inside an html tag. This way you can precisely aim your array'd input:

//Your Holding tag for your inputs!
<div id='input-container' class='funky'></div>

<script>
    //With VAR: you can seperate each variable with a comma instead of:
    //creating var at the beginning and a semicolon at the end.
    //Creates a cleaner layout of your variables
    var
        arr=[['input1-1','input1-2'],['input2-1','input2-2']],
        //globall calls these letters var so you dont have to recreate variable below
        i,j
    ;

    //Instead of the general 'i<array.length' you can go even further
    //by creating array[i] in place of 'i<array.length'
    for(i=0;arr[i];i++){
    for(j=0;arr[i][j];j++){
        document.getElementById('input-container').innerHTML+=
            "<input class='inner-funky'>"+arr[i][j]+"</input>"
        ;
    }}
</script>

Its simply a neater way to write your code and easier to invoke. You can check my demo here!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜