为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

回首忆惘然 2022-06-16 09:55:32
我有这个对象数组来计算另一个数组中的元素频率,使用 for 循环打印正确的输出。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++) {    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){    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循环中获得频率的元素组成。有人能告诉我我哪里错了吗?
查看完整描述

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++;

}


查看完整回答
反对 回复 2022-06-16
?
收到一只叮咚

TA贡献1821条经验 获得超4个赞

我解决了这个问题。问题在于初始化。我更改了以下内容:


var s = counts[holder_text_array[i][1]];

counter = counts[s];

它是这样工作的:


var s = holder_text_array[i][1];

counter = counts[s];


查看完整回答
反对 回复 2022-06-16
?
ABOUTYOU

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]]));


查看完整回答
反对 回复 2022-06-16
  • 3 回答
  • 0 关注
  • 226 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信