如何获得一个匹配值多少次?

时间:2018-06-27 19:24:24

标签: javascript jquery

给出一个数组:

var nationList = ["Austria", "France", "Austria", "Spain", "Austria"]

鉴于以下内容获得了当前的svg path属性(我正在使用http://jsfiddle.net/0jh3fud9/2/,因此该值位于json中)。

var countryName = e.target.feature.properties.name;

我运行以下命令,发现leaflet map,基本上是当我将鼠标悬停在一个多边形上时,得到countryName并检查该数组中有多少次:

var fours = nationList.filter(function(it) {return it === countryName;});
var result = fours.length;

但是,如果我这样做:console.log(result);总是给我10,如果没有匹配项。

在实际情况下,console.log(nationList);的示例给出:

["Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", 

UDPATE

我之前所做的是尝试计算每个值:

  var count = [];
  nationList.sort();
  nationList.forEach(function(i) { 
    var i = i.replace(/^\s+/g, "");
    count[i] = (count[i]||0) + 1;
  });
  console.log(count);

这很好,例如:Austria: 22

但是当我这样做时:

function onEachFeature(feature, layer) {
  layer.on({
    click: selectNation,
    mouseover: printCount
  });
}

function printCount(e) {
  var countryName = e.target.feature.properties.name;
  var filteredNations = nationList.filter( nation => nation ===countryName);
  var result = filteredNations.length;
  console.log(result);
}

每次我用mouse hover pathproperty name时,都说奥地利,甚至在array中,我们也有很多重复出现,如果有匹配项,则console给我10

1 个答案:

答案 0 :(得分:1)

您发布的代码似乎可以正常工作,但是正如GetOffMyLawn所述,您应该将两者以相同的情况进行比较,以确保确定。

var nationList = ["Austria", "France", "Austria", "Spain", "Austria"];
var countryName = e.target.feature.properties.name;
var fours = nationList.filter(
  function(it) {
    return it.toLowerCase() === countryName.toLowerCase();
  });
var result = fours.length;

console.log(result);

很抱歉,答案很短,但目前声誉不足,只能发表评论。