确定JSON数组中的字符串出现

时间:2013-11-13 15:25:53

标签: javascript arrays json string

我有一个字符串化数组:

JSON.stringify(arr) = [{"x":9.308,"y":6.576,"color":"yellow","restitution":0.2,"type":"static","radius":1,"shape":"square","width":0.25,"height":0.25},{"x":9.42,"y":7.488,"color":"yellow","restitution":0.2,"type":"static","radius":1,"shape":"square","width":0.25,"height":0.25}]

我需要找出黄色这个词发生了多少次,所以我可以这样做:

numYellow = 0;
for(var i=0;i<arr.length;i++){
  if(arr[i] === "yellow")
  numYellow++;
}

doSomething = function() {
  If (numYellow < 100) {
    //do something
  }
  If(numYellow > 100) {
    //do something else
  } else { do yet another thing} 
  }

2 个答案:

答案 0 :(得分:1)

数组的每个元素都是一个对象。将arr[i]更改为arr[i].color。这确实假设.color属性是yellow将存在的唯一位置。

答案 1 :(得分:1)

这应该可以解决问题:

var array = [{"x":9.308,"y":6.576,"color":"yellow","restitution":0.2,"type":"static","radius":1,"shape":"square","width":0.25,"height":0.25},{"x":9.42,"y":7.488,"color":"yellow","restitution":0.2,"type":"static","radius":1,"shape":"square","width":0.25,"height":0.25}]

var numYellow = 0;

for(var i=0; i<array.length; i++) {
    if (array[i].color === "yellow") {
        numYellow++;
    }
}