0

I have several divs...

  <div id="foo"></div>
  <div id="bar"></div>

And each has an associated jQuery array. Eg.

var foo_array = ["One", "Two", "Three"];
var bar_array = ["Four", "Five", "Six"];

I want to alert the first value in the related array when I click on the div.

So something like:

$(div).on("click",function(){
   $divid = $(this).attr("id");
   $firstval = ????_array[0];
   alert($firstval);
})

-- where instead of ???? I dynamically echo out the value of $divid. Easy in PHP, but I'm stumped how to do this in javascript?

JohnG
  • 486
  • 3
  • 22

2 Answers2

3

Define the arrays inside a larger object, instead of having multiple standalone variables, and then you can just use property lookup:

const divArrs = {
  foo: ["One", "Two", "Three"],
  bar: ["Four", "Five", "Six"]
}
$('div').on("click", function() {
  divid = $(this).attr("id");
  const firstval = divArrs[divid][0];
  console.log(firstval);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="foo">foo</div>
<div id="bar">bar</div>

Of course, there's no need for jQuery for something like this:

const divArrs = {
  foo: ["One", "Two", "Three"],
  bar: ["Four", "Five", "Six"]
};
document.querySelectorAll('div').forEach((div) => {
  div.onclick = () => {
    console.log(divArrs[div.id][0]);
  };
});
<div id="foo">foo</div>
<div id="bar">bar</div>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • I wouldn't hurry up changing the code's structure – GalAbra Jun 03 '19 at 09:53
  • Thanks - work perfectly as described. I'm afraid I've got a complexifying factor though - I can't declare all the arrays at the same time, so I can't use the same constant. I had tried a similar idea by naming the arrays infoarray[foo], infoarray[bar], but the second just overwrites the info in the first. Any ideas?! – JohnG Jun 03 '19 at 10:22
  • You can create the object after all the arrays are created, if you have to. `const divArrs = { foo: foo_array, bar: bar_array }`, from your original code – CertainPerformance Jun 03 '19 at 10:23
  • In the end I used half of CertainPeformance's answer, but used object literals instead of constants: var myobj = {}; myobj.foo = ["One","Two","Three"]; myobj.bar = ["Four","Five","Six"], and then as above: firstval = myobj[divid][0]; console.log(firstval). – JohnG Jun 03 '19 at 11:02
0

Variables defined globally and with var are automatically accessible in the window object.

var foo_array = ["One", "Two", "Three"];
var bar_array = ["Four", "Five", "Six"];

const id = "foo";
console.log(window[`${id}_array`][0]);
kemicofa ghost
  • 16,349
  • 8
  • 82
  • 131