简体   繁体   English

在JavaScript中访问对象的转义属性

[英]Access escaped properties of an object in javascript

I have an object with a property like this: 我有一个具有这样的属性的对象:

var RouteMetaSet = {

    '\/user-management\/users': {
        path: '/user-management/users',
        name: 'User Management',
        iconClassList: ['fa', 'fa-user'],
    }
};

I can easily get the value of the property like this: 我可以很容易地获得该属性的值,如下所示:

console.log(RouteMetaSet['\/user-management\/users'])

However, if I assign the key to a variable and then push it inside the brackets, it's impossible. 但是,如果我将键分配给变量,然后将其推入方括号内,那是不可能的。

var originialString = /user-management/users;
var escapedString = originialString.replace(/[-/<>*()?]/g, "\\$&"); // it should be "\/user-management\/users"
console.log(RouteMetaSet[escapedString]); // undefined

Am I wrong somewhere on this point? 我在这点上错了吗?

First. 第一。 This: 这个:

var originialString = /user-management/users; var originialString = /用户管理/用户;

… is just syntax errors. ……仅仅是语法错误。

String literals in JS must be quoted. JS中的字符串文字必须加引号。


Next: 下一个:

Escape characters have meaning in JavaScript source code . 转义字符在JavaScript 源代码中具有含义。

When the string literal is parsed by the JavaScript engine it is turned into the string. 当JavaScript引擎解析字符串文字时,它将被转换为字符串。 During this process, the escape characters are consumed. 在此过程中,将使用转义字符。

They aren't part of the data at all. 它们根本不是数据的一部分。 If you insert slashes with regular expressions, then you are just inserting slashes (not escape sequences) into the string. 如果使用正则表达式插入斜杠,那么您只是在字符串中插入斜杠(而不是转义序列)。

 var RouteMetaSet = { '\\/user-management\\/users': { path: '/user-management/users', name: 'User Management', iconClassList: ['fa', 'fa-user'], } }; var originialString = "/user-management/users"; console.log(RouteMetaSet[originialString]); 


Aside: the / character does not need to be escaped in a JS string literal unless it forms part of the sequence </script> inside an inline script. 另外: /字符不需要在JS字符串文字中转义,除非它构成内联脚本中序列</script>一部分。

Generated code often escapes all / characters as a simple and effective way to avoid that problem. 生成的代码通常将所有/字符转义为避免该问题的简单有效的方法。


If the property name included characters that did need to be escaped (such as a \\ ) then, by the time the string had been parsed, it would be too late to sensibly do anything about it. 如果属性名称包含确实需要转义的字符(例如\\ ),那么在解析字符串时,为之明智地做任何事情都为时已晚。

var originalString = "Example\t";

Is that supposed to be a tab or is it supposed to be a \\ followed by a t ? 应该是制表符还是应该是\\然后是t

If you can't trust the code to be right in the first place, you have a problem. 如果您不能一开始就相信代码是正确的,那么您就有问题了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM