How to properly access the value of an array in a callback function?

I am trying to access the value of identifiers [i] correctly inside a function inside a loop. I have tried the following.

This method registers identifiers as a string, I think. I am trying to access it with an index, but it exits undefined. See Console.log inside a simpleWithAttrPrice function call.

for(i=0; i<IDs.length; i++) { console.log("Outside of function Vendor is " + IDs[i]);//logs correctly var optionSelectionArray = currentlySelectedAttributes(IDs[i]); simpleWithAttrPrice(optionSelectionArray, function(data) { //var vendor = IDs[i]; var basePrice = parseFloat(roundDollar(data)); //newPriceArray[vendor][colorSelected]=basePrice; console.log("Vendor is " + IDs);//"5,3" console.log("Vendor is " + IDs[i]);//undefined $j('.details'+IDs[i]+ ' .priceBlock').empty(); $j('.details'+IDs[i]+ ' .priceBlock').append('<span>'+formatCurrency(basePrice,"$")+'</span>'); }); } 

I also tried passing the identifier to the callback function, but it records โ€œsuccessโ€ (literally)

 for(i=0; i<IDs.length; i++) { //var vendor = IDs[i]; var optionSelectionArray = currentlySelectedAttributes(IDs[i]); simpleWithAttrPrice(optionSelectionArray, function(data, IDs) { //var vendor = IDs[i]; var basePrice = parseFloat(roundDollar(data)); //newPriceArray[vendor][colorSelected]=basePrice; console.log("Vendor is " + IDs);//logs ID as "success" ?? $j('.details'+IDs[i]+ ' .priceBlock').empty(); $j('.details'+IDs[i]+ ' .priceBlock').append('<span>'+formatCurrency(basePrice,"$")+'</span>'); }); } 

Finally, I also tried the following, but it adds the price to the same block.

 for(i=0; i<IDs.length; i++) { var vendor = IDs[i]; var optionSelectionArray = currentlySelectedAttributes(vendor); simpleWithAttrPrice(optionSelectionArray, function(data) { var basePrice = parseFloat(roundDollar(data)); //newPriceArray[vendor][colorSelected]=basePrice; console.log("Vendor is " + vendor); //only logs this once. $j('.details'+vendor+ ' .priceBlock').empty();//If I take this away, appends both prices to same block $j('.details'+vendor+ ' .priceBlock').append('<span>'+formatCurrency(basePrice,"$")+'</span>'); }); } 

How to get array identifiers correctly in callback function?

+4
source share
1 answer

@Toby Allen Thank you! Your right to this link. For reference, this works:

 function sendRequest(i) { var optionSelectionArray = currentlySelectedAttributes(IDs[i]); simpleWithAttrPrice(optionSelectionArray, function(data) { //var vendor = IDs[i]; var basePrice = parseFloat(roundDollar(data)); //newPriceArray[vendor][colorSelected]=basePrice; console.log("Vendor is " + IDs);//"5,3" console.log("Vendor is " + IDs[i]);//undefined $j('.details'+IDs[i]+ ' .priceBlock').empty(); $j('.details'+IDs[i]+ ' .priceBlock').append('<span>'+formatCurrency(basePrice,"$")+'</span>'); }); }//end sendRequest for(i=0; i<IDs.length; i++) { sendRequest(i); } 
0
source

Source: https://habr.com/ru/post/1485508/


All Articles