我有兩個數組,如下所示。取兩個數組並將它們變成鍵 - 值對
idOne = ["6", "6", "11"]
counts = ["2", "1", "1"]
我該如何將這做成一個關聯數組,idOne是關鍵和計數是值?
我有兩個數組,如下所示。取兩個數組並將它們變成鍵 - 值對
idOne = ["6", "6", "11"]
counts = ["2", "1", "1"]
我該如何將這做成一個關聯數組,idOne是關鍵和計數是值?
(根據您的意見更新)
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;
}
}
:
var obj = {};
for(var i=0, l=idOne.length; i<l; i++){
obj[idOne[i]] = counts[i];
}
然後,您可以訪問它plalx建議使用包含您的陣列的替代結構進行測試:
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);
}
試試這個:
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);
});
試試這個功能:http://phpjs.org/functions/array_combine/ – jeremy
JavaScript沒有關聯數組。 – undefined
好吧,好吧。我如何使idOne成爲關鍵和計數變量值? – wowzuzz