如果key是RegExp

时间:2016-11-08 03:48:51

标签: javascript regex key object-literal

let ob = {};
ob[/\ing?$/] = `I match all strings end with "ing"`; //key is instance of 'RegEXp'
ob["/\ing?$/"] = `I am sure it is not same as the above`; //key is instance of 'String'

console.log(
`- Key RegExp :
   ==> ${ob[/\ing?$/]}
`);

console.log(
`- Key String :
   ==> ${ob["/\ing?$/"]}
`);

上面的字符串演示了文字对象属性可以是RegExp类的实例,当然它也可以是String,它们完全不同。

我的问题是如何使用Object.keys或替代方法检查类型属性。已知使用Object.keys,此方法将所有键(属性)转换为字符串?

Object.keys(ob);
 //--> Expected :[/\ing?$/, "/\ing?$/"]
 //--> Actual : ["/\ing?$/", "/ing?$/"]

5 个答案:

答案 0 :(得分:2)

属性名称始终是字符串。如果您尝试使用其他内容作为属性名称,则会使用toString()将其转换为字符串。所以当你这样做时:

ob[/\ing?$/] = `I match all strings end with "ing"`; //key is instance of 'RegEXp';

它被视为

ob[/\ing?$/.toString()] = `I match all strings end with "ing"`; //key is instance of 'RegEXp';

所以关键是"/\ing?$/"

当你这样做时:

ob["/\ing?$/"] = `I am sure it is not same as the above`; //key is instance of 'String';

键是字符串"/ing?$/"。反斜杠消失了,因为在字符串文字中,反斜杠是一个转义字符。 \i只是转义了i字符,但由于i没有特殊含义,所以它只是i

如果你想获得与RegExp相同的密钥,它应该是:

ob["/\\ing?$/"] = `I am sure it is not same as the above`; //key is instance of 'String';

双反斜杠会转义反斜杠,因此它会逐字输入字符串。

let ob = {};
ob[/\ing?$/] = `I match all strings end with "ing"`; //key is instance of 'RegEXp';
ob["/\\ing?$/"] = `I am sure it is not same as the above`; //key is instance of 'String';
console.log(ob);

答案 1 :(得分:0)

  

上面的字符串演示了文字对象属性可以是RegExp类的实例

那是错的。所有对象键都是string。任何不是字符串的东西都将转换为字符串。证明可以在下面的代码示例中看到。虽然o1o2不同,但它们都具有相同的字符串表示形式,可用于访问o的属性。

var o1 = {};
o1.toString = function(){return "I am unique";};

var o2 = {};
o2.toString = function(){return "I am unique";};


var o = {};
o[o1] = "foo";



console.log(o[o2]);

答案 2 :(得分:0)

属性在设置时将转换为字符串:

for (var key in ob) {
    console.log('key', key, 'type', typeof key);
}

> key /\ing?$/ type string
> key /ing?$/ type string

答案 3 :(得分:0)

问题RegExp处的javascript与示例字符串不匹配。

let re = /\ing?$/;
console.log(re.test(`I match all strings end with "ing"`));

您可以使用RegExp /(.|)ing?(\1|\.)$/来匹配以inging.结尾的字符串,或"ing"将对象的属性和值定义为{{1} }

RegExp

答案 4 :(得分:0)

由于我是问题的拥有者,我注意到的最佳解决方案是将数据结构从文字对象更改为数组:

来自:

ob = {
   /\ing?$/ : `I match all strings end with "ing"`,
  "/\ing?$/" : `I am sure it is not same as the above`
};

到:

ob = [

   {key: /\ing?$/ , value: `I match all strings end with "ing"` },
   {key:"/\ing?$/" , value: `I am sure it is not same as the above` },  
]

如果是RegExp实例,我们保留密钥的类型。