简体   繁体   English

如何在javascript中实现二维数组的原型函数?

[英]How to implement prototype function with 2 dimensional array in javascript?

I need to implement DataTable struct ,that is in c#, in javascript. 我需要在javascript中实现c#中的DataTable结构。 For example 例如

function Servers(name)
 {
    this.Name = name;
    this.Columns = new Array(5);

    var rows = new Array(3);

    for (var i=0;i<3;i++)
        rows[i]=new Array(5);

    this.Rows = rows;
 }

I simply access jth element of ith Row by typing like this; 我只需输入这样的内容即可访问ith Row的第j个元素;

Servers.Rows[i][j]

This works good, but I need to call my object like this; 这很好用,但我需要这样调用我的对象;

Servers.Rows[i]["ServerUrl"]

But I dont know how to implement a prototype for this work. 但我不知道如何为这项工作实现原型。 Is there anyway to achieve this? 反正有没有实现这个目标?

Note: Columns array holds Column names like in c# and Columns array size always equals to Rows' sub array. 注意:Columns数组保存列名,如c#和Columns数组大小始终等于Rows的子数组。

Live demo 现场演示

 function create2Array(d1, d2, fn) {
    var arr = [],
        d = function(x, y) {},
        f = fn || d;
    for (var i = 0; i < d1; i++) {
        for (var j = 0, curr = []; j < d2; j++) {
             curr[j] = f.call(window, i, j); 
        };
        arr[i] = curr;
    };
    return arr;
};

function createArrayOfObjects(d1) {
    var arr = [];
    for (var i = 0; i < d1; i++) {
        arr[i] = {};
    };
    return arr;
};



function print2DArray(arr) {
    document.body.innerHTML += "<p><b>Array:</b></p>";
    for (var i = 0, len = arr.length; i< len; i++) {
        document.body.innerHTML += "<p><b>" + i + "</b>: " + arr[i].join(" ") + "</p>";
    };
};


function printArrayOfObj(arr) {
    document.body.innerHTML += "<p><b>Array:</b></p>";
    for (var i = 0, len = arr.length; i< len; i++) {
        document.body.innerHTML += "<p><b>" + i + "</b>: " + JSON.stringify(arr[i]) + "</p>";
    };
};

var Server = {};
Server.Rows = createArrayOfObjects(10);
Server.Rows[0]["something"] = "test";
printArrayOfObj(Server.Rows);

Use it like this: 像这样使用它:

Server.rows = create2Array(10, 10);

Or you can even specify a custom init function which takes the index as param. 或者你甚至可以指定一个自定义的init函数,它将索引作为参数。 Say if you want to init your matrix with 0 by default: 假设您是否要默认使用0初始化矩阵:

Server.rows = create2Array(10, 10, function(x, y) { return 0;});

Or if you use an object. 或者如果您使用对象。

Server.rows = create2Array(10, 10);
Server.rows[0]["ServerUrl"] = "test";

You should use a hash/object for this. 你应该使用哈希/对象。

If you want to refer to variables in a data structure by name/string in javascript the an object is the best option. 如果要在javascript中按名称/字符串引用数据结构中的变量,则对象是最佳选项。 See here: https://developer.mozilla.org/en/docs/JavaScript/Guide/Working_with_objects 请参见: https//developer.mozilla.org/en/docs/JavaScript/Guide/Working_with_objects

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM