We're a community of 1.1M IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,080,534 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

JavaScript Array Switching

My project requires that I have several arrays defined in javascript such as:

var d1 = new Array(2,17,18,19,20);
var d2 = new Array(2,18,19,20);
var d3 = new Array(2,18,21,19,20);
var d4 = new Array(2);
var d5 = new Array(2,18,19,20);
var d6 = new Array(2,18,21,19,20);
etc

I have a <select> element which contains options with integer values (1,2,3,4...). When the value of said <select> is changed I need to be able to dynamically switch to the corresponding array.

What is the best way of achieving this?

Edit:
I forgot about the eval function, so I added something like this to test it:

alert(eval('d'+value)[0]);

However, the problem now is that arrays like d4, with only one value in them are showing up as undefined.

2
Contributors
4
Replies
3 Days
Discussion Span
1 Year Ago
Last Updated
5
Views
MysticalNomad
Newbie Poster
7 posts since Nov 2010
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

How about:

var d=[];

    d[1] = [2,17,18,19,20];
    d[2] = [2,18,19,20];
    d[3] = [2,18,21,19,20];
    d[4] = [2];
    d[5] = [2,18,19,20];
    d[6] = [2,18,21,19,20]; 
    //etc..

alert(d[value][0])

will this do what you are aiming for?

Troy III
Master Poster
782 posts since Jun 2008
Reputation Points: 140
Solved Threads: 100
Skill Endorsements: 5

An array of arrays... I actually hadn't considered that! Thank you.

It's true that the longer you look at a problem the more likely the simplest answer is to be overlooked.

MysticalNomad
Newbie Poster
7 posts since Nov 2010
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

it takes years of experience to write simple code.

Troy III
Master Poster
782 posts since Jun 2008
Reputation Points: 140
Solved Threads: 100
Skill Endorsements: 5

So does it solve your problem or not?!

Troy III
Master Poster
782 posts since Jun 2008
Reputation Points: 140
Solved Threads: 100
Skill Endorsements: 5

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page generated in 1.7617 seconds using 2.69MB