[英]create an associative array in jquery
這是我到目前為止, 鞋類型是boots, wellingtons, leather, trainers (in that order)
我想迭代並分配值,所以我有類似的東西
var shoeArray = { boots : '3', wellingtons: '0', leather : '1', trainers: '3'};
目前我只獲得了一個{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;
}
檢查此功能
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:假設$(this).attr('id')
擁有所有鞋子類型
javascript中的關聯數組與object相同
例:
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"]
你想要的是一個將返回一個對象的函數{}
function shoe_types(){
var shoeObj = {};
$('[name="number"]').each(function(){
shoeObj[this.id] = this.value;
});
return shoeObj;
}
shoe_types(); // [object Object]
您可以嘗試在jquery中創建關聯數組
var arr = {};
$('[type=number]').each(function(){
arr.push({
$(this).attr('id'): $(this).val()
});
});
console.log(arr);
這將允許您通過ajax發送您想要通過數組傳遞的所有數據。
如果$(this).attr('id')
是你可以嘗試的那種鞋子
shoeArray[$(this).attr('id')] = parseInt($(this).val());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.