如何在 JavaScript 中将字符串转换为符号 [英] How to convert a String to a Symbol in JavaScript

查看:51
本文介绍了如何在 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);
};

记住 toSymbol("some_string") === toSymbol("some_string")//false(根据规范.你需要保持真实 - 添加记忆)

Keep in mind toSymbol("some_string") === toSymbol("some_string") // false ( by spec. You you need to keep it in true - add memoization )

这篇关于如何在 JavaScript 中将字符串转换为符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆