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

后端 未结 3 459
小鲜肉
小鲜肉 2021-01-07 03:35
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

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-07 03:45

    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'
    

提交回复
热议问题