您可以直接訪問字符串的字符,它的指數使用String.prototype.charAt
方法:
var str = "foo";
for (var i = 0; i < str.length; i++) {
alert(str.charAt(i));
}
但我不認爲你要遍歷您命名空間字符串逐個字符,你可以使用String.prototype.split
方法,來獲得使用點包含命名空間層次陣列(.
)爲分隔符,如:
var levels = "MyCompany.UI.LoginPage".split('.');
// levels is an array: ["MyCompany", "UI", "LoginPage"]
不過我覺得你的問題去進一步此,我會給你一個更先進的出發點,我做了一個遞歸函數,可以讓你做你想要什麼,使用字符串初始化幾個嵌套的對象層次:
使用方法:
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
}
你將不得不提高該功能,例如,你將需要消毒串...
來源
2010-02-22 04:44:25
CMS
有足夠的美元符號呢? – icktoofay 2010-02-22 05:07:30
我認爲使用'substring'獲取只有一個字符是非常昂貴的,當我們有'charAt'方法。 – CMS 2010-02-22 05:09:00
歡迎@Chris,JFTR將字符串轉換爲單字符字符串數組,也可以使用帶空字符串參數的split方法,例如:''foo「.split(」「);'會給你一個看起來像這樣的數組:'[「f」,「o」,「o」]' – CMS 2010-02-22 05:36:33