简体   繁体   English

如何在JavaScript中将字符串转换为符号

[英]How to convert a String to a Symbol in JavaScript

I need to find a way to convert any string to a symbol. 我需要找到一种将任何字符串转换为符号的方法。 If there was a function that did that, it would be something like this: 如果有一个函数可以做到这一点,那就是这样的:

function toSymbol(variable) = {
//... converts var to symbol
};

//toSymbol("mySymbolString") would return: mySymbolString

Is there any clever way of doing this other than storing potential string to symbol mappings in a dictionary? 除了将潜在的字符串到符号映射存储在字典中之外,还有什么聪明的方法吗?

function toSymbol(variable) {
  return Symbol(variable);
};

Keep in mind toSymbol("some_string") === toSymbol("some_string") // false ( by spec. You you need to keep it in true - add memoization ) 请记住toSymbol("some_string") === toSymbol("some_string") // false (根据规范。您需要将其保持为toSymbol("some_string") === toSymbol("some_string") // false添加备注)

I need it to be a variable. 我需要它是一个变量。

All global variables are actually a property of window 所有全局变量实际上都是window的属性

eg: 例如:

window.abc = 123
abc == 123

you can also reference properties using strings, eg: 您还可以使用字符串来引用属性,例如:

window["abc"] = 123
window.abc == 123
abc == 123

If you're using namespaces or objects, then it's just the same, eg: 如果您使用名称空间或对象,则它们是相同的,例如:

My.Namespace["variable"]=value
My.Namespace.variable == value

This gives your example "variable": 这给出了您的示例“变量”:

window["variable"] = value

it's not clear what you want to do with this, but you could make it = null or = {} to use later. 目前尚不清楚您要如何处理,但可以将其设置为= null= {}以供以后使用。

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

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