从“命名空间”构建对象层次结构细绳
我正在尝试编写一个函数,该函数采用表示命名空间的字符串(例如“MyCompany.UI.LoginPage”),并将命名空间的每个段定义为对象(如果它尚不存在)。例如,如果“MyCompany.UI.LoginPage”不是一个对象,它将对此进行评估:
MyCompany = {};
MyCompany.UI = {};
MyCompany.UI.LoginPage = {};
我想通过枚举“命名空间”(字符串)参数的每个字符并在枚举达到句点时定义每个对象来执行此操作人物。
如何在 JavaScript 中枚举字符串的字符?
I'm trying to write a function that takes a string representing a namespace (e.g. "MyCompany.UI.LoginPage") and defines each segment of the namespace as an object if it doesn't already exist. For example, if "MyCompany.UI.LoginPage" wasn't an object, it would evaluate this:
MyCompany = {};
MyCompany.UI = {};
MyCompany.UI.LoginPage = {};
I would like to do this by enumerating each character of the "namespace" (string) argument and defining each object as the enumeration reaches period characters.
How can I enumerate the characters of a string in JavaScript?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 < 直接通过索引访问字符串的字符code>String.prototype.charAt 方法:
但我不认为你想逐个字符地遍历你的命名空间字符串,你可以使用
String.prototype.split
方法,获取包含命名空间级别的数组,使用点(.
)字符作为分隔符,例如:但我认为您的问题进一步到此,我将为您提供一个更高级的起点,我创建了一个递归函数,该函数将允许您完全执行您想要的操作,使用字符串初始化多个嵌套对象级别:
用法:
实现:
您必须改进此功能,例如您需要清理字符串......
You can access the characters of a string directly by its index, using the
String.prototype.charAt
method:But I don't think that you want to traverse your namespace string character by character, you can use the
String.prototype.split
method, to get an array containing the namespace levels using the dot (.
) character as a separator, e.g.:But I think your question goes further to this, and I will give you a more advanced starting point, I made a recursive function that will allow you to do exactly what you want, initialize several nested object levels using a string:
Usage:
Implementation:
You will have to improve this function, for example you will need to sanitize the string...
使用以下代码将字符串转换为字符数组:
然后您可以枚举字符串数组中的每个字符
$letterArrary
Convert the string into an array of characters with this code:
Then you can enumerate over each character in the string array
$letterArrary