How to use a RegExp literal as object key?

前端 未结 4 2101
野的像风
野的像风 2020-12-13 18:34

I would like to use create a object that contains regular expressions as the key value. I tried to use the following syntax:

var kv = {
    /key/g : \"value\         


        
4条回答
  •  -上瘾入骨i
    2020-12-13 18:48

    Object keys cannot be RegExp objects. You must use a string or a valid ID. That being said, you could do something like this:

    var kv = {
        "/key/g": "value"
    };
    

    I'm curious. Why do you want to do this?

    EDIT: I am partially mistaken. RegExp objects can be used as keys, but not using the object literal syntax. See jmar777's answer.

提交回复
热议问题