1

Is it possible to change the array, trough which is looped with an external variable, which gives the array-name as string?

My example loops through the variable name itself. I guess this is just a syntax-question? Thanks a lot for your help.

HTML

<ul>
    <li data-array="one">Array One</li>
    <li data-array="two">Array Two</li>
    <li data-array="three">Array Three</li>
</ul>

JS

var one = ['One-One','One-Two','One-Three'];
var two = ['Two-One','Two-Two','Two-Three'];
var three = ['Three-One','Three-Two','Three-Three'];

$('li').click(function(){

  var selectedArray = $(this).attr('data-array');

  for (var i = 0; i < selectedArray.length; i++) {
    console.log(selectedArray[i]);
  }
});

https://jsfiddle.net/Loeevw51/

0

2 Answers 2

1

Referencing to a variable by having its name as string can be done using eval(), but if you have reached the point where you need to do this, you should redesign your code.

A much simpler, faster and cleaner solution is to use an object (if that's an option):

var arrays =
{
    one: ['One-One','One-Two','One-Three'],
    two: ['Two-One','Two-Two','Two-Three'],
    three: ['Three-One','Three-Two','Three-Three']
};

Then you can use arrays['one'] or arrays.one to access its elements.
Updated fiddle.

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

Comments

0

You can access your variables by using the window object. That assumes however, that the variables are global variables (as is the case in your example).

Change your loop to the following:

for (var i = 0; i < window[selectedArray].length; i++) {
    console.log(window[selectedArray][i]);
}

Demo: https://jsfiddle.net/cre0vjk6/

1 Comment

This only works when the code is directly wrapped in head or body, which wasn't the case in OP's fiddle.

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.