How to convert a String to a Symbol in JavaScript

痴心易碎 提交于 2019-12-11 22:12:24

问题


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?


回答1:


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 )




回答2:


I need it to be a variable.

All global variables are actually a property of 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.



来源:https://stackoverflow.com/questions/37511572/how-to-convert-a-string-to-a-symbol-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!