JavaScript数组语法

时间:2011-11-30 15:09:35

标签: javascript arrays

var selectColumns = new Array();
selectColumns[0] = { TableName: "DeploymentRosterView", ColumnName: "ArrivedOn" };
selectColumns[1] = { TableName: "DeploymentRosterView", ColumnName: "DepartedOn" };
selectColumns[2] = { TableName: "DeploymentRosterView", ColumnName: "RoleType" };
selectColumns[3] = { TableName: "DeploymentRosterView", ColumnName: "AdjusterFirstName" };
selectColumns[4] = { TableName: "DeploymentRosterView", ColumnName: "AdjusterLastName" };

上面的工作是用JavaScript创建我的数组,但有没有更优雅的方式来编写上述内容?像对象初始化器一样?只是想知道

3 个答案:

答案 0 :(得分:10)

您可以内联创建:

var selectColumns = [
    { TableName: "DeploymentRosterView", ColumnName: "ArrivedOn" },
    { TableName: "DeploymentRosterView", ColumnName: "DepartedOn" },
    { TableName: "DeploymentRosterView", ColumnName: "RoleType" },
    { TableName: "DeploymentRosterView", ColumnName: "AdjusterFirstName" },
    { TableName: "DeploymentRosterView", ColumnName: "AdjusterLastName" }];

答案 1 :(得分:1)

你可以创建一个像:

这样的数组
var selectColumns = [
    { TableName: "DeploymentRosterView", ColumnName: "ArrivedOn" },
    { TableName: "DeploymentRosterView", ColumnName: "DepartedOn" },
    { TableName: "DeploymentRosterView", ColumnName: "RoleType" },
    { TableName: "DeploymentRosterView", ColumnName: "AdjusterFirstName" },
    { TableName: "DeploymentRosterView", ColumnName: "AdjusterLastName" }
];

答案 2 :(得分:1)

你可以这样重组:

var selectColumns = {

  "DeploymentRosterView": {
    "ColumnNames": ["DepartedOn", "RoleType", "AdjusterFirstName", "AdjusterLastName"]
  }
};

// Loop through all views
for (view in selectColumns)
{
  var v = selectColumns[view].ColumnNames;
  alert('Column names for "' + view + '" is: ' + v.join(', '));
}​