LeB*_*eau 13 javascript arrays jquery associative-array
这是我迄今为止和鞋的类型是boots, wellingtons, leather, trainers (in that order)
我想迭代并分配值,所以我有类似的东西
var shoeArray = { boots : '3', wellingtons: '0', leather : '1', trainers: '3'};
Run Code Online (Sandbox Code Playgroud)
目前我只是得到一个{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;
}
Run Code Online (Sandbox Code Playgroud)
zzl*_*ani 23
检查此功能
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;
}
Run Code Online (Sandbox Code Playgroud)
PS:假设$(this).attr('id')有所有的鞋类型
小智 8
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"]
Run Code Online (Sandbox Code Playgroud)
你想要的是一个将返回一个对象的函数 {}
function shoe_types(){
var shoeObj = {};
$('[name="number"]').each(function(){
shoeObj[this.id] = this.value;
});
return shoeObj;
}
shoe_types(); // [object Object]
Run Code Online (Sandbox Code Playgroud)