问题加载和访问2D数组

时间:2015-05-28 05:16:33

标签: javascript c# jquery arrays

在jquery / javascript中,数组具有以下结构。我可以使用data [cartIndex] .rows [i]。

来获取数据
//cartIndex is anything from 0 to 10;
//row is like [name, quantity, balance, remarks]

for (var i=0; i < data[cartIndex].length; i++) {
            var row = data[cartIndex].rows[i];
            alert(row.name, row.quantity, row.balance);
}

我使用了列表和数组来填充C#中的数据并将其序列化。

更新代码:

        var arrList = new List<object>();

        string x = string.Empty;
        int i = table.Rows.Count;
        foreach (DataRow row in table.Rows)
        {
            string name = row[0].ToString();
            string quantity = row[1].ToString();
            string balance = row[2].ToString();
            string remove = "X";

            arrList.Add(new Wrapper { rows = new [] { name, quantity, balance, remove }});
        }

        var maList = new List<object>();
        maList.Add(arrList);            
        return (new JavaScriptSerializer()).Serialize(maList);

但不知何故,它不是javascript中正确的列行格式。

data = [
         [[name, quantity, balance, remarks], 
            [name, quantity, balance, remarks], 
            [name, quantity, balance, remarks]
         ],
         [[name, quantity, balance, remarks], 
            [name, quantity, balance, remarks], 
            [name, quantity, balance, remarks]
         ]         
       ]

有了这个,我无法像这样访问数组行:

var row = data[cartIndex].rows[i];
//row.name gives name, row.quantity gives quantity and so on

此结构还应允许将行推入数组。

data[cartIndex].length++;
data[cartIndex].rows.push({name: name, 
quantity: quantity, balance: blance});

如何通过行索引构建要访问的c#数组?

1 个答案:

答案 0 :(得分:2)

您可以像这样访问第二维中的数据:

var name= data[cartIndex][0];
var quantiry = data[cartIndex][1];
// And so on...

属性data[cartIndex].rows不起作用,因为从服务器端添加到列表的对象没有属性rows

或者,您可以按如下方式更改服务器代码:

// Add a new wrapper class
public class Wrapper{
    public string[] rows{ get;set;}
}

并将添加行的行更改为列表,如下所示:

alist.Add(new Wrapper { rows = new [] {name, quantity, balance, remove}});