Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/400.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在javascript中按字符串名称设置变量?_Javascript - Fatal编程技术网

在javascript中按字符串名称设置变量?

在javascript中按字符串名称设置变量?,javascript,Javascript,显然,这不起作用。如果我只想获取变量的值,而不是设置它,那么它就可以工作 //window["Fluent"]["Include"] function setGlobalVariableByName(name,value) { var indexes = name.split("."); var variable = null; $.each(indexes, function() { if (variable == null){

显然,这不起作用。如果我只想获取变量的值,而不是设置它,那么它就可以工作

//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
如果不使用eval,我如何实现这样的目标?
我想,我需要一些方法以编程方式将数组索引添加到这个函数中


下面的工作,你能建议一个更好的方法来编码,以使它更干燥

window["Fluent"]["Include"]["JqueryPulse"] = true;
console.log(Fluent.Include.JqueryPulse) // prints true

你需要打电话

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;
    }
}
不知怎么的。因此,您需要在记录姓氏之前中断拆分字符串的循环,然后分配值

最后,您需要致电:

variable[this] = value 

最终,您只需构建一个对象链,并将链中的最后一项设置为值。此外,我还将添加一个检查,以确保已经是对象的项不会被覆盖,从而使其现有属性不会丢失:

variable = window['Fluent']['Include']; // build this in a loop
variable['JqueryPulse'] = someValue; // then call this
但是,即使页面上有jQuery,我也不会使用jQuery。不需要为每个
索引执行函数的开销

//bootstrap the object for demonstration purposes--not necessary to make code work
window.Fluent = {
  Include: {
    foo: 'bar', //don't want to lose this'
    JqueryPulse: false //want to set this to true
  }
};

//define function
function setGlobalItemByName( name, value )
{
  var names,
      finalName,
      //no need to figure out if this should be assigned in the loop--assign it now
      currentOp = window;

  if( typeof name === 'string' && name !== '' )
  {
    names = name.split( '.' );
    //no need to track where we are in the looping--just pull the last off and use it after
    finalName = names.pop();

    $.each( names, function()
    {
      //If the current item is not an object, make it so. If it is, just leave it alone and use it
      if( typeof currentOp[this] !== 'object' || currentOp[this] === null )
      {
        currentOp[this] = {};
      }

      //move the reference for the next iteration
      currentOp = currentOp[this];
    } );

    //object chain build complete, assign final value
    currentOp[finalName] = value;
  }
}

//use function
setGlobalItemByName( 'Fluent.Include.JqueryPulse', true );


//Check that Fluent.Include.foo did not get lost
console.log( Fluent.Include.foo );
//Check that Fluent.Include.JqueryPulse got set
console.log( Fluent.Include.JqueryPulse );
//出于演示目的引导对象--不需要使代码正常工作
window.Fluent={
包括:{
foo:'酒吧',//不想失去这个'
JqueryPulse:false//要将其设置为true吗
}
};
//定义函数
函数setGlobalItemByName(名称、值)
{
变量名称,
最终名称,
indexCount,
当前索引,
当前名称,
//不需要弄清楚是否应该在循环中分配它--现在就分配它
currentOp=窗口;
if(typeof name=='string'&&name!='')
{
name=name.split('.');
//不需要跟踪我们在循环中的位置——只需拔出最后一个,然后使用它
finalName=names.pop();
indexCount=names.length;
对于(currentIndex=0;currentIndex
它们确实存在,我只是这样解释了这个问题。变量
Fluent.Include.JqueryPulse
已经存在,值为false,我想将其设置为true。但是我不需要初始化任何东西这里有一个不同的版本:@Nico-你说,“变量Fluent.Include.JqueryPulse已经在那里了…”小心不要踩踏已经存在于该链中的对象,因为你会丢失它们的属性。请参阅我的答案和代码注释以避免该问题。
//bootstrap the object for demonstration purposes--not necessary to make code work
window.Fluent = {
  Include: {
    foo: 'bar', //don't want to lose this'
    JqueryPulse: false //want to set this to true
  }
};

//define function
function setGlobalItemByName( name, value )
{
  var names,
      finalName,
      //no need to figure out if this should be assigned in the loop--assign it now
      currentOp = window;

  if( typeof name === 'string' && name !== '' )
  {
    names = name.split( '.' );
    //no need to track where we are in the looping--just pull the last off and use it after
    finalName = names.pop();

    $.each( names, function()
    {
      //If the current item is not an object, make it so. If it is, just leave it alone and use it
      if( typeof currentOp[this] !== 'object' || currentOp[this] === null )
      {
        currentOp[this] = {};
      }

      //move the reference for the next iteration
      currentOp = currentOp[this];
    } );

    //object chain build complete, assign final value
    currentOp[finalName] = value;
  }
}

//use function
setGlobalItemByName( 'Fluent.Include.JqueryPulse', true );


//Check that Fluent.Include.foo did not get lost
console.log( Fluent.Include.foo );
//Check that Fluent.Include.JqueryPulse got set
console.log( Fluent.Include.JqueryPulse );
//bootstrap the object for demonstration purposes--not necessary to make code work
window.Fluent = {
  Include: {
    foo: 'bar', //don't want to lose this'
    JqueryPulse: false //want to set this to true
  }
};

//define function
function setGlobalItemByName( name, value )
{
  var names,
      finalName,
      indexCount,
      currentIndex,
      currentName,
      //no need to figure out if this should be assigned in the loop--assign it now
      currentOp = window;

  if( typeof name === 'string' && name !== '' )
  {
    names = name.split( '.' );
    //no need to track where we are in the looping--just pull the last off and use it after
    finalName = names.pop();

    indexCount = names.length;
    for( currentIndex = 0; currentIndex < indexCount; currentIndex += 1 )
    {
      currentName = names[currentIndex];

      //If the current item is not an object, make it so. If it is, just leave it alone and use it
      if( typeof currentOp[currentName] !== 'object' || currentOp[currentName] === null )
      {
        currentOp[currentName] = {};
      }

      //move the reference for the next iteration
      currentOp = currentOp[currentName];
    }

    //object chain build complete, assign final value
    currentOp[finalName] = value;
  }
}

//use function
setGlobalItemByName( 'Fluent.Include.JqueryPulse', true );


//Check that Fluent.Include.foo did not get lost
console.log( Fluent.Include.foo );
//Check that Fluent.Include.JqueryPulse got set
console.log( Fluent.Include.JqueryPulse );