JavaScript杂技:此代码使用eval,如何删除它?

时间:2010-11-11 22:09:30

标签: javascript jquery

这个部分代码我入侵了JamieMThomas's JQuery plugin,它结合了Microsoft JQuery模板和链接插件(模板中的声明性链接)。我想引用像"A[0].B[0].C[0].myProperty"这样的变量树。您可以跳到底部,因为我将其放入以供参考:

var extVar = $.extend({ name: elem.name }, 
                      { convert: binding.converter.convertBack, 
                                 convertBack: binding.converter.convert });

                       // binding.field is a string pointing to a variable to map
var a = binding.field.match(/([A-Z]+)\[\d+\]/g);     // Find all array references

 // If we have arrays, we need to create the corresponding hierarchy in "mapping"
if ( a != null)
{    b = mapping;            // mapping (object) will reference a variable to map
     for( i = 0; i < a.length; i++)                       // for each array found
     {    var arr = a[i].match(/[A-Z]+/);                         // array's name
          b[arr] = [];               // make mapping match our binding.field text
          var idx = a[i].match(/\d+/g);                            // index value
          if( a[i+1] !== undefined )                 // is the next item an array?
              b[arr][idx] = [];                           // Yes, match the array
          else
              b[arr][idx] = {};                            // No, match an object
          b = b[arr][idx] ; // Reference LPC[x]       // reference the next child
     }
}

eval('(mapping.' + binding.field + ' = eval("extVar") )');

底部的eval最终运行以下代码。你如何重写这个不包括eval语句?

mapping.A[2].B[1].C[5].myProperty = A[2].B[1].C[5].myProperty;

1 个答案:

答案 0 :(得分:4)

在javascript中,正如您可以object[propertyName]阅读内容,您可以object[propertyName] = value分配内容。

其余的就在这里:How to turn this JavaScript string "myArray[0].myPrice" in to a reference to myPrice?

基本上:

var data = mapping,
    chain = binding.field.split(/[\.\[\]]+/);

// If the last character of binding.field is `]` we'll get "" in the end of chain
if (!chain[chain.length - 1]) { 
    chain.splice(-1);
}

var n = chain.length;
for (var i = 0; i < n - 1; i++) {
    data = data[chain[i]];      
}

data[chain[n - 1]] = extVar;

// Embrace JavaScript Awesomeness!