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. 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]);
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.
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
. A common way to get around this is to call a function that accepts i
as a parameter that will return a function.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.