如何像开发人员控制台一样计算数组中的项

How to count the items in array like the developer console

本文关键字:计算 一样 数组 开发 何像 控制台      更新时间:2023-09-26

脚本:

vL1 = ["AB", "AB", "AB", "AB", "AB", "CS", "CS", "CS", "ND", "ND"];
vL2 = ["1",  "1",  "1",  "2",  "3",  "1",  "1",  "2",  "1",  "1"];
for(var i = 0; i < vL1.length; i++){
    thing = vL1[i] + " " + vL2[i];
    console.log(thing);
}

当我检查开发人员控制台时,我看到以下内容:

(3) AB 1
    AB 2
    AB 3
(2) CS 1
    CS 2
(2) ND 1

如何修改脚本,以便获得代码中出现AB1CS1的次数,以便用于其他函数?

我只想知道vL1中表示的每个vL2的计数。关联vL1很重要,因为这将使我能够识别vL2,因为它不是唯一的。

您还可以执行以下操作;

var vL1 = ["AB", "AB", "AB", "AB", "AB", "CS", "CS", "CS", "ND", "ND"],
    vL2 = ["1",  "1",  "1",  "2",  "3",  "1",  "1",  "2",  "1",  "1"],
 result = vL1.reduce((p,c,i) => p[c] ? (p[c][vL2[i]] = p[c][vL2[i]] ? ++p[c][vL2[i]]
                                                                    : 1, p)
                                     : (p[c] = {[vL2[i]]: 1}, p), {});
console.log(result);

您可以将计数存储在对象中。此外,使用Array.prototype.reduce可以使使用索引变得更简单(例如,您不必手动处理索引的递增等(:

    vL1 = ["AB", "AB", "AB", "AB", "AB", "CS", "CS", "CS", "ND", "ND"];
vL2 = ["1",  "1",  "1",  "2",  "3",  "1",  "1",  "2",  "1",  "1"];
var counts = vL1.reduce(function(counts,vL1Element,index) {
  //initialize this index if it isn't set
  if(counts[vL1Element] == undefined) {
    counts[vL1Element] = {};
  }
  //set this count to 0 if it hasn't been set yet
  if (counts[vL1Element][vL2[index]] == undefined) {
    counts[vL1Element][vL2[index]] = 0;
  }
    counts[vL1Element][vL2[index]]++;
  return counts;
},{});
console.log(counts);

var obj={};
function log(a){
 if(obj[a]){
  obj[a]++;
 }else{
  obj[a]=0;
 }
 }

然后做:

log(thing);

在你的for循环内部,然后:

console.log(obj);

Obj现在包含:AB1:3;…