这个助手$ .each()函数如何赋值?

时间:2014-06-21 08:45:18

标签: javascript jquery

有人请解释这个功能的一部分是如何运作的?

var result = {}

$.each(this.serializeArray(), function(i, v) {
    result[v.name] = v.value;
});

从上面的代码中,我不明白以下内容:

result[v.name] = v.value;

我不明白这是如何给我得到的结果,这是一个具有名称值对的对象。这是怎么回事?

1 个答案:

答案 0 :(得分:2)

// result is defined as empty object
var result = {}


// your each binding most likely is inside a $('form').submit(function(){ in here });
// so this.searializeArray() converts ( whatever "this" is in your scope )  an JavaScript array of objects you iterate over where function(i <- is the key, v <- is the object)

$.each(this.serializeArray(), function(i, v) {
    // so for every object in your array you take the value and assign a new object in your initial empty result object with object.name as key and object.value as value 
    result[v.name] = v.value;
});

// so result may look like this after that

result ==   { 
"fooname":"foovalue",
"barname":1337
}