当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - can I set a regexp for an object's method/property selector?

问题描述:

var regxp = /[\S]/; //any char, not sure if it's /.*/ or something else

var obj = {

atr1: "bla"

}

var blahs = obj[regxp]; //returns atr1

I'm looking for a shortcut to get methods/properties names from an object, because for..in is slow compared to a for loop for instance.

I want this for a special case when I know the object will have only one method/property

网友答案:

Yes, you can try to access a property of an object using a regular expression but no, it won't do what you want: it will convert the regex into a string and use that property name.

The only way to find a property name on an object by matching a regular expression is a for ... in loop, like you mentioned. The performance should not be an issue if the object has only one property.

function findPropertyNameByRegex(o, r) {
  for (var key in o) {
    if (key.match(r)) {
      return key;
    }
  }
  return undefined;
};
findPropertyNameByRegex(obj, regxp); // => 'atr1'
网友答案:

your regex will match a single non-space character.

for...in is a loop. it's slower than what exactly? have you benchmarked?

if you want to look up properties using a regex, you'll have to do it in a loop.

for(var k in obj) {
    if(regexp.match(k)) {
      // do whatever
    }
}
网友答案:

If you have only one property, you can be pretty sure for..in will not be slow.

分享给朋友:
您可能感兴趣的文章:
随机阅读: