Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在javascript数组中添加新列_Javascript_Arrays - Fatal编程技术网

在javascript数组中添加新列

在javascript数组中添加新列,javascript,arrays,Javascript,Arrays,我有一个包含三列的数组,如下所示: data.push({ country: new Date(), newSales: Math.random() * 1000, expenses: Math.random() * 5000 }); var cols = { country: new Date(), newSales: Math.random() * 1000, expenses: Math.random() * 5000 }; 现在,单击按钮,我想在其中添加一个新

我有一个包含三列的数组,如下所示:

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

现在,单击按钮,我想在其中添加一个新列。有人能告诉我怎么做吗?

请检查“推送”方法:

您可以迭代数据数组并向每个元素添加键和值

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


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

data.push({
  country: new Date(),
    newSales: Math.random() * 1000,
     expenses: Math.random() * 5000
 });
var cols = { country: new Date(), newSales: Math.random() * 1000, expenses: Math.random() * 5000 };
然后说,, 数据推送(cols)

现在,在按钮逻辑中,向对象添加一个新列(或者更确切地说是属性),如下所示:

obj.newCol = 'some value';
这将自动反映在数组中

//伪代码

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

这是我向二维数组添加列的方法

我为谁而分享

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: "" });
    }
}
insertColumnAtRight(){
对于(var i=0;i

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

如果看到我的代码,我已经在使用push方法插入项。我的问题是如何在数组中添加新列。不是新项目。希望现在清楚。如果要在数据的第一个元素中添加新属性,请尝试
data[0]。newcolumnname='which value'