1

我曾经使用以下方法过滤我的功能:

for (var i=0; i<features.length; i++) 
 { 
 if (features[i].attributes.color == 'blue') 
. 
. 

但有时值可能是:深蓝色,浅蓝色..等所以我使用了匹配但仍然无法正常工作:

var x = "blue"; 
 if (features[i].attributes.color.match(new RegExp(x, "ig"))) 

我收到此错误:

Cannot call method 'match' of undefined 
4

1 回答 1

1

似乎某些功能没有设置颜色属性。运行,例如:

for (var i=0; i<features.length; i++) 
    console.log(typeof features[i].attributes.color);

您可以在未定义的属性上使用 ==,但不能在其上运行函数,这就解释了为什么== 'blue'不抛出错误。

var foo = {bar: 'Test'};
// That doesn't throw error
if (foo.baz == 'blue') console.log('Is blue');
// And that throws error
if (foo.baz.match(new RegExp('blue', 'ig'))) console.log('Is blue');

所以你应该首先测试是否设置了颜色属性,然后测试它:

for (var i=0; i<features.length; i++) 
    if (features[i].attributes.color && features[i].attributes.color == 'blue') ...
于 2012-12-16T15:25:36.327 回答