gpt4 book ai didi

javascript - JS : using eval on a function while trying to pass an array as parameter, 但它抛出一个错误

转载 作者:行者123 更新时间:2023-11-30 23:42:12 26 4
gpt4 key购买 nike

我想使用 javascript 创建一个动态生成的表单,一切正常,直到我尝试传递一个数组作为参数。当我这样做时,会发生错误。谁能解释一下这是什么?

这是我的代码:

var loadFrm = function(component) {
for(nItem in component) {
var myComponent = "add" + firstToUpper(component[nItem].type);
var callComponent = myComponent + "(" + component[nItem].opt + ");";
eval(callComponent);
}
}

var json = [
{
type: "scale",
opt: {content: [{label: "male", value: "m"}, {label: "female", value: "f"}]}
}
];

loadFrm(json);

编辑这是错误:

missing ] after element list
[Break on this error] addScale([object Object]);

最佳答案

如果您使用调试器查看字符串callComponent ,您可能会发现它看起来像这样:

addScale([object Object])

...which isn't what you want. That's because you're effectively calling toString on your opt object, and the default toString on objects just looks like that. The eval error is because that's invalid syntax.

Generally speaking, any time you think you need to use eval, there's almost certainly a better answer. In this case, it looks like you're trying to call a function and pass in opt. Assuming these functions are "globals", you can do that like this:

var loadFrm = function(component) {
var nItem, functionName;

for (nItem = 0; nItem < component.length; ++nItem) {
functionName = "add" + firstToUpper(component[nItem].type);
window[functionName](component[nItem].opt);
}
}

Live example

以上注释:

  1. 请勿使用for..in循环遍历数组,除非你 really know what you're doingfor..in不枚举数组的索引,而是枚举对象的属性。
  2. 我们使用 window[functionName] 按名称查找函数。这是有效的,因为“全局变量”实际上是 window 的属性。对象,并且您可以使用括号表示法使用字符串名称查找属性。
  3. 已通过 window[functionName] 获取该功能,我们直接调用它,传入对象 opt而不是它的字符串形式。我假设addScale期望看到一个物体。
  4. 我移动了所有 var s 到函数的顶部,因为那是它们真正所在的位置 ( details )。
  5. 如果可以的话,我建议搬家 addScale以及相关的函数到它们自己的对象,而不是把它们放在window上。 window命名空间已经相当拥挤了。 Here's the live example修改为不向 window 添加任何符号根本不用,而是输入 addScale名为 functions 的对象上的函数并从那里使用它。
<小时/>

离题:语法 var loadFrm = function(component)创建一个匿名函数,然后将其分配给一个变量。这被经常使用,但除非您根据条件创建不同的函数,例如:

var f;
if (...) {
f = function() { ... };
}
else {
f = function() { ... };
}

...实际上并没有什么用处。 (如果您根据这样的条件创建不同的函数,那么它不仅有用,而且是必要的。)我 recommend using named functions只要有可能,因为带有名称的函数可以帮助您的工具通过在错误消息、调用堆栈等中显示函数名称来帮助您。

离题 2:您有一个名为 json 的变量,但仅供引用,它没有使用 JSON符号。它使用 JavaScript 数组和对象文字表示法的组合,这是 JSON 的超集。你会看到很多人对此感到困惑,我提到它是因为你说你是新人,所以值得将其消灭在萌芽状态。 :-) JSON 纯粹是一种表示法。 (非常有用的一个。)

关于javascript - JS : using eval on a function while trying to pass an array as parameter, 但它抛出一个错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4254118/

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