Javascript 将数据推送到具有对值的数组中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11773225/
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
push data into an array with pair values
提问by Andrei Ion
how can I push data into an array in js if it's type is likw this... d= [[label, value]]. At first I want to push the label data then the values.... I get the data from an xml file. If I had only a simple array I used the simple variable.push sintax. Will varialble[][0].push or variable[][1].push work
如果数据类型是这样的,我如何将数据推送到 js 中的数组中... d= [[label, value]]。起初我想推送标签数据然后是值....我从一个 xml 文件中获取数据。如果我只有一个简单的数组,我会使用简单的 variable.push sintax。varialble[][0].push 或 variable[][1].push 会起作用吗
回答by LmC
Maybe you would be better of using an object,
也许你会更好地使用一个对象,
So you could do
所以你可以这样做
var d = {
"Label" : "Value"
};
And to add the value you coud
并添加您可以使用的价值
d.label = "value";
This might be a more structure approach and easier to understand if your arrays become big. And if you build the JSON valid its easisy to make a string and parse it back in.
如果您的数组变大,这可能是一种更结构化的方法并且更容易理解。如果您构建 JSON 有效,则可以轻松创建字符串并将其解析回。
Like var stringD = JSON.stringify(d); var parseD = JSON.parse(stringD);
喜欢 var stringD = JSON.stringify(d); var parseD = JSON.parse(stringD);
UPDATE - ARRAY 2D
更新 - 阵列 2D
This is how you could declare it
这就是你可以声明它的方式
var items = [[1,2],[3,4],[5,6]];
alert(items[0][0]);
And the alert is reading from it,
警报正在读取它,
To add things to it you would say items[0][0] = "Label" ; items[0][1] = "Value";
要添加东西,你会说 items[0][0] = "Label" ; items[0][1] = "Value";
If you want to do all the labels then all the values do..
如果你想做所有的标签,那么所有的值都做..
for(var i = 0 ; i < labelssize; i ++)
{
items[i][0] = labelhere;
}
for(var i = 0 ; i < labelssize; i ++)
{
items[i][1] = valuehere;
}
回答by xdazz
You could do like this:
你可以这样做:
var d = [];
d.push([label, value]);
回答by Pedro L.
What you need is a an array of objects.
你需要的是一个对象数组。
Imagine this sample XML:
想象一下这个示例 XML:
<?xml version="1.0"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
</book>
</catalog>
Your data structure could be:
您的数据结构可能是:
var catalog = array(
{
'id': 'bk101',
'author': 'Gambardella, Matthew',
'title': 'XML Developer\'s Guide',
'genre': 'Computer'
},
{
'id': 'bk102',
'author': 'Ralls, Kim',
'title': 'Midnight Rain',
'genre': 'fantasy'
}
);
Then, you can acces the data like an array. Sample operations:
然后,您可以像访问数组一样访问数据。示例操作:
Read value:
读取值:
var genre = catalog[0]['genre'];
Add a new property:
添加新属性:
catalog[1]['price'] = '15.50';
List all titles:
列出所有标题:
for (var i=0; i<catalog.length; i++) {
console.log(catalog[i]['title'];
}