0

我有一个字符串化数组:

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} 
  }
4

2 回答 2

1

数组的每个元素都是一个对象。更改arr[i]arr[i].color。不过,这确实假设该.color物业是唯一yellow存在的地方。

于 2013-11-13T15:28:47.243 回答
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++;
    }
}
于 2013-11-13T15:32:40.537 回答