我可以为对象的方法/属性选择器设置正则表达式吗? [英] 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
我正在寻找从对象获取方法/属性名称的快捷方式,因为 for..in
与for循环相比较慢。
当我知道对象只有一个方法/属性时我想要这个特例
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.
通过匹配正则表达式在对象上查找属性名称的唯一方法是 for ... in
循环,就像你提到的那样。如果对象只有一个属性,性能应该不是问题。
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'
这篇关于我可以为对象的方法/属性选择器设置正则表达式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!