在Javascript中打印对象数组的元素

我有这个对象数组来计算另一个数组中的元素频率,使用 for 循环打印正确的输出。


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: ',counts[s]); //prints undefined

        counter = counts[s];

    }

i++;

}

数组“holder_text_array”的数组由我需要在while循环中获得频率的元素组成。有人能告诉我我哪里错了吗?


回首忆惘然
浏览 227回答 3
3回答

胡子哥哥

频率存储在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 dynamicallyfor (var x = 0, y = counter_array.length; x < y; x++) {&nbsp; &nbsp; 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 arrayvar p = "a";var i = 0;while(i < holder_text_array.length){&nbsp; &nbsp; if (holder_text_array[i][0]==p) {&nbsp; &nbsp; &nbsp; &nbsp; var s = counts[holder_text_array[i][1]];&nbsp; &nbsp; &nbsp; &nbsp; console.log('Element: ', holder_text_array[i][1]); //prints 50 for i = 0&nbsp; &nbsp; &nbsp; &nbsp; console.log('frequency: ', s); // CHANGED THIS TO JUST `s`&nbsp; &nbsp; &nbsp; &nbsp; counter = counts[s];&nbsp; &nbsp; }i++;}

收到一只叮咚

我解决了这个问题。问题在于初始化。我更改了以下内容:var s = counts[holder_text_array[i][1]];counter = counts[s];它是这样工作的:var s = holder_text_array[i][1];counter = counts[s];

ABOUTYOU

您可以采用递归方法并为具有相同counts对象的(嵌套)数组再次调用 count 函数。结果包含每个元素的计数。function getCounts(array, counts = {}) {&nbsp; &nbsp; for (let i = 0; i < array.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; const value = array[i];&nbsp; &nbsp; &nbsp; &nbsp; if (Array.isArray(value)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; getCounts(value, counts);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (!counts[value]) counts[value] = 0;&nbsp; &nbsp; &nbsp; &nbsp; counts[value]++;&nbsp; &nbsp; }&nbsp; &nbsp; return counts;}console.log(getCounts([["a", 50, 0], ["b", 0, 0]]));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript