最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to convert a String to a Symbol in JavaScript - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question asked May 29, 2016 at 15:17 mechanical-turkmechanical-turk 8012 gold badges8 silver badges9 bronze badges 3
  • Possible duplicate of What does this symbol mean in JavaScript? – brianlmerritt Commented May 29, 2016 at 15:22
  • 1 Do you mean a Symbol, as in: developer.mozilla/en/docs/Web/JavaScript/Reference/… Or do you mean to a variable? – fdomn-m Commented May 29, 2016 at 15:42
  • @freedomn-m i meant it in the second sense. i need it to be a variable. thanks for pointing out the confusion. – mechanical-turk Commented May 29, 2016 at 16:09
Add a ment  | 

2 Answers 2

Reset to default 4
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 )

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.

发布评论

评论列表(0)

  1. 暂无评论