gpt4 book ai didi

JavaScript 杂技 : This code uses eval, 怎么去掉呢?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:51:23 26 4
gpt4 key购买 nike

这部分代码我黑进了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;

最佳答案

在 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!

关于JavaScript 杂技 : This code uses eval, 怎么去掉呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4159747/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com