Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/408.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_Object_Function Parameter - Fatal编程技术网

Javascript 参数是以函数作为属性初始化对象时变量的名称,而不是其值

Javascript 参数是以函数作为属性初始化对象时变量的名称,而不是其值,javascript,object,function-parameter,Javascript,Object,Function Parameter,我试图初始化一个对象的属性,一个是函数。 如果我将其硬编码为: subitems = { "1" : { "label": "Link1", "action": function(obj) {showURL(obj,"http://link1.com")} }, "2" : { "label": "Link2", "action": function(obj) {showURL(obj,"http://link2.com")}

我试图初始化一个对象的属性,一个是函数。 如果我将其硬编码为:

subitems = {
   "1" : { "label": "Link1",
           "action": function(obj) {showURL(obj,"http://link1.com")}
   },
   "2" : { "label": "Link2",
           "action": function(obj) {showURL(obj,"http://link2.com")}
   }
}
或者,如果我尝试使用变量中的列表动态执行此操作

subitemdata = [['Link1','http://link1.com'],['Link2','http://link2.com']];
我使用它来填充标签和动作属性并生成对象

subitems = {};
for (i=0; i<subitemdata.length;i++) {
    subitems[i] = {};
    subitems[i].label = subitemdata[i][0];
    subitems[i].action = function(obj) {showURL(obj,subitemdata[i][1])};
}
如何编写代码,使“action”属性中的字符串“subitemdata[I][1]”不会出现在函数“showURL”的参数列表中,但“subitemdata”列表“”和“”中的实际值会出现

使用动态方式初始化对象时,我无法重新创建硬编码的对象版本

subitem[i].action = (function makeConstantStr(str){
    //this takes the array, gets the value and returns a new function with
    //the current value in the array as the 2nd argument of the innermost function
    return function(obj) {showURL(obj,str)};
}(subitemdata[i][1]));
如果将其包装在立即调用的函数中并传入值,则应立即对其求值,并且参数将设置为数组内容的值,而不是数组引用本身

不过,为了确保清楚,只要不修改subitemdata,数组引用在使用它时将返回相同的内容。除非希望在特定时刻保持数组的值,否则不需要这样做

如果将其包装在立即调用的函数中并传入值,则应立即对其求值,并且参数将设置为数组内容的值,而不是数组引用本身


不过,为了确保清楚,只要不修改subitemdata,数组引用在使用它时将返回相同的内容。您不需要这样做,除非您希望在特定时刻保留数组的值。

第4行缺少逗号?我假设子项和子项[I]之间存在差异是拼写错误吗?我不太明白你的问题…@David He似乎希望showURL中的第二个参数是一个常量,设置为子项[I][1]的初始值,而不是对它的引用。是的,缺少的逗号和子项[I]与子项[I]是拼写错误,我现在更正了。第4行缺少逗号?我假设子项和子项[I]之间的差异是一个打字错误?我不完全理解你的问题…@David He似乎希望showURL中的第二个参数是一个常量,设置为子项[I][1]的初始值,而不是对它的引用。是的,缺少逗号和子项[I]与子项[i] 是打字错误,我现在改正了。
subitem[i].action = (function makeConstantStr(str){
    //this takes the array, gets the value and returns a new function with
    //the current value in the array as the 2nd argument of the innermost function
    return function(obj) {showURL(obj,str)};
}(subitemdata[i][1]));