//window["Fluent"]["Include"]
function setGlobalVariableByName(name,value)
{
var indexes = name.split(".");
var variable = null;
$.each(indexes, function()
{
if (variable == null){
variable = window[this];
}else{
variable = variable[this];
}
});
variable = value;
}
setGlobalVariableByName("Fluent.Include.JqueryPulse",true);
console.log(Fluent.Include.JqueryPulse) // prints false
這顯然不起作用。如果我只是想獲得變量的值,但不能設置它,它會起作用。在JavaScript中通過字符串名稱設置變量?
window["Fluent"]["Include"]["JqueryPulse"] = true;
console.log(Fluent.Include.JqueryPulse) // prints true
我怎麼能達到這樣的東西,而不使用eval?
我需要一些方法來數組索引編程方式添加到這一點,我猜
下面的作品,你可以提出一個更好的辦法了,爲了使它更幹代碼?
function setGlobalVariableByName(name,value)
{
var indices = name.split(".");
var parent;
$.each(indices, function(i)
{
if(i==indices.length-1){
if (!parent){
window[this] = value;
}else{
parent[this] = value;
}
}else if (!parent){
parent = window[this];
}else{
parent = variable[this];
}
});
}
setGlobalVariableByName : function(name, value)
{
var indices = name.split(".");
var last = indices.pop();
var parent;
$.each(indices, function(i)
{
if (!parent){
parent = window[this];
}else{
parent = variable[this];
}
});
if (!parent){
window[last] = value;
}else{
parent[last] = value;
}
}
他們確實存在,我只是這樣解釋它的問題。變量'Fluent.Include.JqueryPulse'已經存在,其值爲假,我想將其設置爲true。但我不需要初始化任何東西 – bevacqua
以下是不同的版本:http://jsfiddle.net/3WtJM/2/ –
@Nico - 你說過,「變量Fluent.Include.JqueryPulse已經存在了...」小心你不要跺腳那些已經存在的物品,因爲你會失去它們的屬性。查看我的回答和代碼註釋以避免此問題。 – JAAulde