[英]javascript dynamic array creation with key value pairs
I am trying to create dynamic array while selecting values from various select boxes. 我试图从各种选择框中选择值时创建动态数组。 So I want the created array's key and value should be the value and text of as selected.
因此,我希望创建的数组的键和值应为选定的值和文本 。
for example below are three select boxes for Name, grade and age. 例如,以下是三个选择框,分别是名称,年级和年龄。
Name grade age
--------- --------- ---------
Jack A 12
Sam B 13
Jessy A 11
I tried the below code: 我尝试了以下代码:
<script>
var data = [];
$('.filter_select').change(function() {
data[$(this).attr('name')] = $(this).val();
});
</script>
But I am not able to iterate the created array for using $.each(data, function() {}); 但是我无法使用$ .each(data,function(){});来迭代创建的数组。
Whenever I do selecting any of the three select boxes the array should be look like this and can be iterated using $.each 每当我选择三个选择框中的任何一个时,数组应该看起来像这样,并且可以使用$ .each进行迭代。
var data = []
data['Name'] = 'Sam'
data['grade'] = 'A'
data['age'] = '12'
Any help could lead right way. 任何帮助都可以正确引导。
Use var data = {};
使用
var data = {};
if you only need key/value pairs and don't need array capabilities. 如果您只需要键/值对而不需要数组功能。 Iterating properties could be done like this:
迭代属性可以这样完成:
for (var property in data) {
// your code accessing data[property]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.