问题描述
我正在尝试编写一个函数,该函数接受表示命名空间的字符串(例如MyCompany.UI.LoginPage),并将命名空间的每个段定义为对象(如果它尚不存在)。例如,如果MyCompany.UI.LoginPage不是对象,它将评估此:
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 = {};
我想通过枚举namespace(string)参数的每个字符并定义每个对象作为枚举到达句点字符。
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.
如何在JavaScript中枚举字符串的字符?
How can I enumerate the characters of a string in JavaScript?
推荐答案
您可以使用方法:
You can access the characters of a string directly by its index, using the String.prototype.charAt
method:
var str = "foo";
for (var i = 0; i < str.length; i++) {
alert(str.charAt(i));
}
但我认为你不想遍历名称空间字符串逐个字符,您可以使用方法,使用点(。$)获取包含命名空间级别的数组c $ c>)字符作为分隔符,例如:
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.:
var levels = "MyCompany.UI.LoginPage".split('.');
// levels is an array: ["MyCompany", "UI", "LoginPage"]
但是我认为你的问题进一步到这个,我会给你一个更高级的起点,我做了一个递归函数,它将允许你完全按照自己的意愿,初始化几个嵌套使用字符串的对象级别:
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:
用法:
initializeNS('MyCompany.UI.LoginPage');
// that will create a MyCompany global object
// you can use it on an object to avoid globals also
var topLevel = {};
initializeNS('Foo.Bar.Baz', topLevel);
// or
var One = initializeNS('Two.Three.Four', {});
实施:
function initializeNS(ns, obj) {
var global = (function () { return this;})(), // reference to the global object
levels = ns.split('.'), first = levels.shift();
obj = obj || global; //if no object argument supplied declare a global property
obj[first] = obj[first] || {}; // initialize the "level"
if (levels.length) { // recursion condition
initializeNS(levels.join('.'), obj[first]);
}
return obj[first]; // return a reference to the top level object
}
你必须改进这个函数,例如你需要清理字符串......
You will have to improve this function, for example you will need to sanitize the string...
这篇关于从“命名空间”字符串构建对象层次结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!