[英]Compare a value with all the values in array in Javascript
I am trying to make the following function run but I have stucked badly. 我试图使以下功能运行,但是我严重卡住了。 I have an object "gidsAll" which I want to compare with each feature: feature.attributes.__gid.
我有一个对象“ gidsAll”,我想与每个功能部件进行比较:feature.attributes .__ gid。
The function is used in Openlayers for styling purpose of the features (points and lines). 该功能在Openlayers中用于样式化特征(点和线)的目的。 It is executed for each "feature.attributes.__gid" and what I want is to simple compare this value with all the values inside the "gidsAll".
它对每个“ feature.attributes .__ gid”都执行,我想要的是简单地将此值与“ gidsAll”中的所有值进行比较。 If the value matches one of the value in "gidsAll" then return green otherwise return red.
如果该值与“ gidsAll”中的值之一匹配,则返回绿色,否则返回红色。
I think I need to use a loop somewhere but I can not make it work. 我认为我需要在某个地方使用循环,但无法使其正常工作。
var styleContext = {
getColor: function (feature) {
//alert(typeof(feature));//object
// for (key in gidsAll){
if (Math.round(feature.attributes.__gid) == Number(gidsAll)){
return "green";
} else {
return "red";
}
//}
}
};
You should check all the properties in the object before you return red
, because you need to make sure there are no green
matches. 返回
red
之前,应检查对象中的所有属性,因为您需要确保没有green
匹配项。 Note, that return "red"
is outside the loop: 请注意,
return "red"
在循环之外:
var styleContext = {
getColor: function (feature) {
for (key in gidsAll) {
if (Math.round(feature.attributes.__gid) == Number(gidsAll)) {
return "green";
}
}
return "red";
}
};
You can use Object.keys()
to loop over all the objects properties. 您可以使用
Object.keys()
遍历所有对象属性。
Object.keys
returns all the enumerable object's own properties of the object it receives.Object.keys
返回接收到的对象的所有可枚举对象自己的属性。
var styleContext = {
getColor: function (feature) {
var objectKeys = Object.keys(gidsAll);
for (var i = 0; i < objectKeys.length; i++)
{
if (Math.round(feature.attributes.__gid) === parseInt(gidsAll[objectKeys[i]], 10))
{
return "green";
}
}
return "red"; //nothing has been found
//}
}
Just another version using ES5 Object.keys and Array.prototype.some methods: 只是使用ES5 Object.keys和Array.prototype.some方法的另一个版本:
var styleContext = {
getColor: function (feature) {
return Object.keys(gidsAll).some(function (p) {
return Math.round(feature.attributes.__gid) == gidsAll[p];
})? 'green' : 'red';
}
};
If you do this a lot, use a loop as it's faster, but keys and some are concise. 如果您经常这样做,请使用循环,因为这样做更快,但是按键和某些 按键简明扼要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.