简体   繁体   English

数组返回0长度,在html中无法调用

[英]Array return 0 length, unable to call it in html

I am calling ticketCountData in html, but it returns nothing, the reason is that array length is 0.我在html中调用ticketCountData,但是什么也没返回,原因是数组长度为0。

result - main array with all data,结果 - 包含所有数据的主数组,

In bellow script I am checking how many times unique names appears in the array and I return the number of it:在下面的脚本中,我正在检查数组中出现的唯一名称的次数,并返回它的数量:

result.forEach((row) => {
    if(!(row['Owner'] in ticketCountData))
        ticketCountData[row['Owner']] = 0;

    ticketCountData[row['Owner']] += 1;

})
console.log(ticketCountData);

Array shows correct data, yet it length is 0. I can check length of it by数组显示正确的数据,但它的长度为 0。我可以检查它的长度

console.log(Object.keys(ticketCountData).length);

Yet I am not sure how to call value that is in the array, which looks like that:但是我不确定如何调用数组中的值,如下所示:

Array(0)
"": 10
john.smith1: 18
john.smith2: 13
john.smith3: 21
john.smith4: 24

Thanks!谢谢!

You need to understand that your ticketCountData is NOT an array - it is an object.您需要了解您的 ticketCountData 不是一个数组 - 它是一个 object。 The square brackets in javascript can be used in different ways, specifically you need to know that these two expressions are identical: javascript中的方括号可以有不同的使用方式,具体你需要知道这两个表达式是相同的:

ob.name='andrew';
ob['name']='andrew';

So your code runs perfectly but produces an object that has unique names as a key and the count as values.因此,您的代码运行完美,但生成了一个 object,其具有唯一名称作为键,计数作为值。 Generally to turn this into an array containing the name and the count you would do something like this:通常要将其转换为包含名称和计数的数组,您可以执行以下操作:

let countDataList=Object.keys(ticketCountData).map((key)=> ({
       name:key,
       count: ticketCountData[key],
   }))

You should use the function hasOwnProperty of JS.你应该使用JS的function hasOwnProperty

result.forEach((row) => {
    if(!ticketCountData.hasOwnProperty(row['Owner']) ){
        ticketCountData[row['Owner']] = 0;
    }

    ticketCountData[row['Owner']] += 1;
})

console.log(ticketCountData);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM