在 jquery 中创建关联数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19787868/
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
create an associative array in jquery
提问by LeBlaireau
This is what I have so far and the shoe typesare boots, wellingtons, leather, trainers (in that order)
这是我到目前为止所拥有的鞋子类型是boots, wellingtons, leather, trainers (in that order)
I want to iterate through and assign the value so I haves something like
我想遍历并分配值,所以我有类似的东西
var shoeArray = { boots : '3', wellingtons: '0', leather : '1', trainers: '3'};
at the moment I just get an array of {3,0,1,3}
which I can work with but it is not very helpful.
目前我只是得到一个{3,0,1,3}
我可以使用的数组,但它不是很有帮助。
function shoe_types() {
var shoeArray = [];
$('[type=number]').each(function(){
$('span[data-field='+$(this).attr('id')+']').text($(this).val());
shoeArray.push ( parseInt($(this).val()) );
});
return shoeArray;
}
回答by zzlalani
Check this function
检查这个功能
function shoe_types() {
var shoeArray = {}; // note this
$('[type=number]').each(function(){
$('span[data-field='+$(this).attr('id')+']').text($(this).val());
shoeArray[$(this).attr('id')] = parseInt($(this).val()) ;
});
return shoeArray;
}
PS: Assuming $(this).attr('id')
has all the shoe types
PS:假设$(this).attr('id')
有所有鞋型
回答by Mykyta Shyrin
Associative array in javascript is the same as object
javascript中的关联数组与对象相同
Example:
例子:
var a = {};
a["name"] = 12;
a["description"] = "description parameter";
console.log(a); // Object {name: 12, description: "description parameter"}
var b = [];
b["name"] = 12;
b["description"] = "description parameter";
console.log(b); // [name: 12, description: "description parameter"]
回答by Roko C. Buljan
回答by Dushyant Dagar
You can try this to create an associate array in jquery
你可以试试这个在jquery中创建一个关联数组
var arr = {};
$('[type=number]').each(function(){
arr.push({
$(this).attr('id'): $(this).val()
});
});
console.log(arr);
This will allow you to send your all data whatever you want to pass in array by ajax.
这将允许您通过 ajax 发送您想要在数组中传递的所有数据。
回答by jbduzan
if $(this).attr('id')
is the type of shoes you can try that
如果$(this).attr('id')
是你可以尝试的鞋子类型
shoeArray[$(this).attr('id')] = parseInt($(this).val());