我有一个字符串化的数组:
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}
}发布于 2013-11-13 23:28:47
数组的每个元素都是一个对象。将arr[i]更改为arr[i].color。但是,这确实假设yellow将存在的惟一位置是.color属性。
发布于 2013-11-13 23:32:41
这应该能起到作用:
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++;
}
}https://stackoverflow.com/questions/19957667
复制相似问题