Moritz
Moritz

Reputation: 766

Use string to set name of array

I would like to set one array equal to another via a string. I have the following array:

var apartment234 = ["01.07.2017","02.07.2017","03.07.2017","04.07.2017","05.07.2017","06.07.2017","07.07.2017"];

And I have the following string which equals the array above (apartment234).

unavailable = "apartment" + ausgewzimmer;

If I now want a function to return something based on the array as shown below, it doesn't return anything.

return !!(unavailable.indexOf(date.format('DD.MM.YYYY')) > -1);

However, if I use the array directly, it does work.

return !!(apartment234.indexOf(date.format('DD.MM.YYYY')) > -1);
//returns desired values

I am not sure what I am doing wrong... unavailable does equal apartment234 as in unavailable = "apartment234". Why doesn't it function? Could you please help me?

Upvotes: 0

Views: 134

Answers (3)

Lacruiser
Lacruiser

Reputation: 1

If you only need to have string-representation of your array as return of function calls, can't you just do regular Array.toString() and String.split(",") methods to handle this?

Upvotes: 0

HaukurHaf
HaukurHaf

Reputation: 13796

The string "apartment234" is not the same as the array instance apartment234.

When you do this:

unavailable.indexOf(....)

You are just calling the indexOf() method on the string.

You could use the eval() method to accomplish this:

unavailable = eval("apartment" + ausgewzimmer);

eval() evaluates, or executes the given string as JS code.

Upvotes: 1

Satpal
Satpal

Reputation: 133403

Define a object with property "apartment234", then it can be accessed using bracket notation.

var obejct = {
  "apartment234": ["01.07.2017", "02.07.2017", "03.07.2017", "04.07.2017", "05.07.2017", "06.07.2017", "07.07.2017"]
};

var unavailable = "apartment" + 234;
console.log(obejct[unavailable]);

Upvotes: 2

Related Questions