1

次のように2つの配列があります。

idOne =  ["6", "6", "11"]
counts =  ["2", "1", "1"]

これを idOne がキーで counts が値の連想配列にするにはどうすればよいでしょうか?

4

3 に答える 3

3

(updated based on your comments)

var totalsByID = {};
for(var i = 0; i < idOne.length; i++) {
   var id = idOne[i];
   var count = parseInt(counts[i]);
   if(totalsByID[id] === undefined) {
      // We have no entry for this ID, so create one
      totalsByID[id] = count;
   } else {
      // We already have an entry for this ID, so we need to add our current count to it
      totalsByID[id] += count;
   }
}

plalx suggested an alternate structure that includes your arrays for testing:

var idOne = ["6", "6", "11"],
    counts = ["2", "1", "1"],
    totalsById = {},
    i = 0,
    len = idOne.length,
    k;

for(; i < len; i++) {
   k = idOne[i];

   //initialize the total to 0
   totalsById[k] = totalsById[k] || 0;

   //you could remove the parseInt call if your count values were numbers instead of strings
   totalsById[k] += parseInt(counts[i], 10);
}
于 2013-03-29T21:29:10.417 に答える
1

これを実現するには、オブジェクトを使用する必要があります。

var obj = {};
for(var i=0, l=idOne.length; i<l; i++){
  obj[idOne[i]] = counts[i];
}

その後、次の方法でアクセスできます。

obj['6']; // -> 1
于 2013-03-29T21:27:04.040 に答える
1

これを試して:

idOne = ["6", "6", "11"]
counts = ["2", "1", "1"]

var dict = []; // create an empty array
$.each(idOne, function (index, value) {
    dict.push({
        key: idOne[index],
        value: counts[index]
    });
});

console.log(dict);

次のようにキーと値のペアにアクセスできます。

$.each(dict, function (index, data) {
    console.log(data.key + " : " + data.value);
});
于 2013-03-29T21:48:32.293 に答える