3 回答
TA贡献1825条经验 获得超6个赞
频率存储在snot incounts[s]
你在counts[s]哪里记录var s = counts[holder_text_array[i][1]];
您已经从countsin 中获得了元素s。只需记录的值s
除此之外,该功能有效!
counts = {};
counter = 0;
counter_array = [50,50,0,200]; //this is just for example, this array is filled dynamically
for (var x = 0, y = counter_array.length; x < y; x++) {
counts[counter_array[x]] = (counts[counter_array[x]] || 0) + 1;
}
console.log('FREQUENCY: ',counts); //outputs FREQUENCY: {50:2, 0:1, 200:1}
holder_text_array = [["a",50,0],["b",0,0]]; //example of dynamically filled array
var p = "a";
var i = 0;
while(i < holder_text_array.length){
if (holder_text_array[i][0]==p) {
var s = counts[holder_text_array[i][1]];
console.log('Element: ', holder_text_array[i][1]); //prints 50 for i = 0
console.log('frequency: ', s); // CHANGED THIS TO JUST `s`
counter = counts[s];
}
i++;
}
TA贡献1821条经验 获得超4个赞
我解决了这个问题。问题在于初始化。我更改了以下内容:
var s = counts[holder_text_array[i][1]];
counter = counts[s];
它是这样工作的:
var s = holder_text_array[i][1];
counter = counts[s];
TA贡献1812条经验 获得超5个赞
您可以采用递归方法并为具有相同counts对象的(嵌套)数组再次调用 count 函数。
结果包含每个元素的计数。
function getCounts(array, counts = {}) {
for (let i = 0; i < array.length; i++) {
const value = array[i];
if (Array.isArray(value)) {
getCounts(value, counts);
continue;
}
if (!counts[value]) counts[value] = 0;
counts[value]++;
}
return counts;
}
console.log(getCounts([["a", 50, 0], ["b", 0, 0]]));
添加回答
举报