14

这是我到目前为止所拥有的,鞋子类型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;        
}
4

5 回答 5

28

检查此功能

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')拥有所有鞋型

于 2013-11-05T11:30:48.800 回答
9

javascript中的关联数组与对象相同

例子:

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"]
于 2013-11-05T11:30:37.973 回答
7

你想要的是一个返回对象的函数 {}

现场演示

function shoe_types(){
   var shoeObj = {};
   $('[name="number"]').each(function(){
     shoeObj[this.id] = this.value;
   });
   return shoeObj;
}

shoe_types(); // [object Object]
于 2013-11-05T11:42:52.553 回答
2

你可以试试这个在jquery中创建一个关联数组

var arr = {};
$('[type=number]').each(function(){
    arr.push({
         $(this).attr('id'): $(this).val()              
     });
});

console.log(arr);

这将允许您发送所有数据,无论您想通过 ajax 在数组中传递什么。

于 2017-09-01T10:08:53.387 回答
0

如果$(this).attr('id')是那种鞋,你可以试试

shoeArray[$(this).attr('id')] = parseInt($(this).val());
于 2013-11-05T11:29:54.697 回答