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

这个部分代码我入侵了JamieMThomas的 JQuery 插件 ,该插件结合了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(/([AZ]+)\[\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(/[AZ]+/); // 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; 

在javascript中,正如你可以做object[propertyName]来读取东西你可以做object[propertyName] = value来分配东西。

剩下的就在这里: 如何将这个JavaScript字符串“myArray [0] .myPrice”转换为对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!