[英]Passing object array - Unexpected token [
function showConfirm(reArray) {
var theHTML = '';
var optionArray = ["Option 1", "Option 2", "Option 3", "Option 4", "Option 5", "Option 6", "Option 7"];
var myButtons = {};
var j = 1;
for(var i = 0; i < reArray.length; i++){
theHTML +='<div style="text-align:center">'
+ '<span>'+j+'.</span> '
+ '<span>'+reArray[i].RoadNo+'</span> '
+ '<span>'+compass_image(reArray[i].Bearing)+'</span> '
+ '</div><br/>'
j++;
}
for(i = 0; i < reArray.length; i++){
ERROR HERE -----> var placeFunction = function(reArray[i]){
plotRoadInfo(reArray[i]);
$(this).dialog("close");
};
myButtons[optionArray[i]] = placeFunction;
}
$( "#dialog-modal" ).dialog({
height: 300,
modal: true,
buttons: myButtons
});
$('#multipleRE').append(theHTML);
}
So the function gets passed an object array (reArray), it then creates an array of buttons (myButtons) for a jquery dialog box. 因此,该函数将传递一个对象数组(reArray),然后为一个jquery对话框创建一个按钮数组(myButtons)。 I'm attempting to to pass reArray[i] to the function that will be used by each button, which is to execute plotRoadInfo(reArray[i]);
我试图将reArray [i]传递给每个按钮将要使用的函数,该函数将执行plotRoadInfo(reArray [i]);。
I keep getting "Unexpected token [", and I can't figure out why for the life of me. 我不断收到“意外令牌[”,但我不知道为什么要为我的生命而死。
You don't specify the type of a parameter in JavaScript, simply use the name and then use it as an array in your function. 您无需在JavaScript中指定参数的类型,只需使用名称,然后将其用作函数中的数组即可。
var placeFunction = function(reArray){
plotRoadInfo(reArray[i]);
$(this).dialog("close");
};
I don't think you even need to specify it though as you're referring to as array that the inner function has access to. 我认为您甚至不需要指定它,因为当您将其称为内部函数可以访问的数组时。
var placeFunction = function() {
plotRoadInfo(reArray[i]);
$(this).dialog("close");
};
As Pointy notes this will run in to issues with the i
variable being shared so each function will refer to reArray[reArray.length]
because the loop will complete when i === reArray.length
. 正如Pointy指出的那样,这将遇到共享
i
变量的问题,因此每个函数都将引用reArray[reArray.length]
因为在i === reArray.length
时循环将完成。 A common way to get around this is to call a function that accepts i
as a parameter that will return a function. 解决此问题的常用方法是调用一个接受
i
作为参数的函数,该函数将返回一个函数。
var placeFunction = (function (item) {
return function() {
plotRoadInfo(item);
$(this).dialog("close");
};
}(reArray[i]));
Read up on closures for a deeper understanding of how this works. 阅读有关闭包的内容,以更深入地了解其工作原理。 Here is another example of this happening.
这是发生这种情况的另一个示例 。
The syntax you have is incorrect. 您使用的语法不正确。
I believe what you want to do is the following: 我相信您要执行的操作如下:
var placeFunction =
(function(arrayitem){
return function(){
plotRoadInfo(arrayitem);
$(this).dialog("close");
};
})(reArray[i]);
myButtons[optionArray[i]] = placeFunction;
Why does the parameter have an index? 为什么参数有索引?
function(reArray[i])
did you mean 你的意思是
function(reArray)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.