0

How can I pass a array name into a function and read values dynamically?

Dynamically i have generated array as follows

fruits[0] = "Banana";
fruits[1] = "Orange";
fruits[2] = "Apple";

//Hyperlink to activate function below

I have a function in hyeperlink <a href="javascript: activate('1', 'fruits')">Click Me</a>

Below is the function

function activate(idNumber, arrayName)
{
  alert('id is:'+ idNumber); **//Working** 
  alert(arrayName[idNumber]); **//Not working must print fruits[1]**

}
0

2 Answers 2

2

It depends on the scope in which 'fruits' is defined.

Assuming it is global, window[arrayName] will get it when arrayName=='fruits'. This is because window holds a reference to all global objects.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot Bro! you saved my day! This one exactly fixed my problem! Cheers!!
1

You are passing in the letters "f","r","u","i","t", and "s" instead of the variable, just remove the quotes from around the variable:

<a href="javascript: activate('1', fruits)">Click Me</a>

2 Comments

HI Kranklin, Yes i did try passing fruits directly but it says undefined now
Where are you defining fruits? Is your code exactly like what you have or do you have a line like fruits = [] that is before the assignments? If not then just try fruits = ["Banana", "Orange", "Apple"]. Otherwise a jsfiddle.net would be nice to help figure out what's wrong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.