Javascript 在javascript数组中添加新列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28208732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
add new column in javascript array
提问by Ashish
I have an array containing three columns like this:
我有一个包含三列的数组,如下所示:
data.push({
country: new Date(),
newSales: Math.random() * 1000,
expenses: Math.random() * 5000
});
Now, on button click, I want to add a new column in it. Can anyone let me know how we can do it?
现在,在单击按钮时,我想在其中添加一个新列。任何人都可以让我知道我们如何做到这一点?
回答by Sruti
You could iterate though the data array and add key & value to each element.
您可以遍历数据数组并向每个元素添加键和值。
data[0]["foo"] = bar; // this can be useful if the key is not constant
or
或者
data[0].foo = "bar"
回答by Neetu
You could define the columns in your array in a separate object like this:
您可以在一个单独的对象中定义数组中的列,如下所示:
var cols = { country: new Date(), newSales: Math.random() * 1000, expenses: Math.random() * 5000 };
Then say, data.push(cols);
然后说, data.push(cols);
Now in your button logic, add a new column (or rather property) to the object as follows:
现在在您的按钮逻辑中,向对象添加一个新列(或属性),如下所示:
obj.newCol = 'some value';
This will then be automatically reflected in your array
这将自动反映在您的数组中
回答by AZBlue
// Pseudocode
// 伪代码
for i in data
data[i].foo = "bar"
回答by Tobi
Please check the "push"-method: http://www.w3schools.com/jsref/jsref_push.asp
请检查“推送”方法:http: //www.w3schools.com/jsref/jsref_push.asp

