在javascript数组中添加新列

时间:2015-01-29 07:00:07

标签: javascript arrays

我有一个包含三列的数组:

data.push({
  country: new Date(),
    newSales: Math.random() * 1000,
     expenses: Math.random() * 5000
 });

现在,点击按钮,我想在其中添加一个新列。谁能让我知道我们怎么做呢?

5 个答案:

答案 0 :(得分:9)

您可以遍历数据数组并添加键和;每个元素的价值。

data[0]["foo"] = bar; // this can be useful if the key is not constant

data[0].foo = "bar"

答案 1 :(得分:1)

您可以在单独的对象中定义数组中的列,如下所示:

var cols = { country: new Date(), newSales: Math.random() * 1000, expenses: Math.random() * 5000 };

然后说,     data.push(COLS);

现在在按钮逻辑中,按如下方式向对象添加新列(或更确切地说属性):

obj.newCol = 'some value';

然后会自动反映在您的数组中

答案 2 :(得分:1)

这是我将列添加到二维数组的方式。

我为关心的人分享了

var textarray = [[{ text: 'Content 1' }, { text: 'Content 2' }], 
                 [{ text: 'Content 3' }, { text: 'Content 4' }]];

将列添加为右侧数组的方法

insertColumnAtRight() {
    for (var i = 0; i < this.textarray.length; i++) {
      this.textarray[i].push({ text: "" });
    }
}

如果要在左侧添加列,可以使用unshift方法而不是push

答案 3 :(得分:0)

请检查“推送”方法:http://www.w3schools.com/jsref/jsref_push.asp

答案 4 :(得分:0)

// Pseudocode

for i in data
    data[i].foo = "bar"