0

At present I have a list of conditional statements such as:

if(x = 1) { $(#div).html('A') };

if(x = 2) { $(#div).html('B') };

if(x = 3) { $(#div).html('C') };

if(x = 4) { $(#div).html('D') };

This does the job but isn't very efficient.

I'm trying to take a DRY approach to this but am unsure of how to go about it.

I'm wondering if something similar to the following will work or if there's a better way to achieve this.

var arr = [
    [1, 'A'],
    [2, 'B'],
    [3, 'C'],
    [4, 'D']
]

if ( x === arr[any of sub arrays][0]{ // 1, 2, 3 or 4

    $('div#').html('[triggered sub array[1]'); // if 1 is triggered, set html content to A, if 2, set html content to B and so on.    
}

Is there a term for what I'm trying to describe here so I can look it up?

2
  • div# seems like a syntax error, since it implies you're selecting a <div> coupled with a zero-length id property, and an id must be both unique and have a length of one, or more, characters. Commented Feb 26, 2015 at 23:37
  • I think it was probably just shorthand for "divId", another way of putting a "foobar" placeholder. Commented Feb 26, 2015 at 23:56

1 Answer 1

2

I may be misunderstanding you, but...sounds like you could just use a map?

var map = {
  1: 'A',
  2: 'B',
  3: 'C'
};

if (map.hasOwnProperty(incomingNum)) {
  $('div#').html(map[incomingNum));
}
Sign up to request clarification or add additional context in comments.

2 Comments

This is exactly what I needed (I know the other comments are correct too, thanks guys!). I'm quite new to arrays, maps & objects with JavaScript.
A map is just an object, we just call it a map because it serves a specific role in our minds.

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.