1

Here is code that I have copied from w3schools, I have different code, but the problem that I am having still happens in this simplified coding.

<!DOCTYPE html>
<html>
<body>

<p id="demo">Click the button to create an array, then display it's length</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction()
{
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var foods = ["steak","pizza","bread","fruits"];
var x=document.getElementById("demo");
var y=foods[3];
x.innerHTML= y.length;
}
</script>

</body>
</html>

When I do x.innerHTML= fruits.length;, I get 4 back which is what I want to get.

But when I call

var y=foods[3];
x.innerHTML= y.length;

I get 6 which is the length of the word "fruits" but I want the length of the array fruits.

How do I do this?

I'm using jQuery, don't know if that affects anything. Do I have to add parenthesis or brackets somewhere?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Dropoff510
  • 51
  • 2
  • 7
  • No, you don't have to add parenthesis, you just have to query `fruits` instead of `foods`. Unless there's something I'm missing. – Mr Lister Jan 20 '13 at 20:13
  • 2
    **Please!** [Don't use w3schools to teach you *anything*](http://w3fools.com/)! – Joseph Silber Jan 20 '13 at 20:14
  • possible duplicate of [Is there a way to access a javascript variable using a string that contains the name of the variable?](http://stackoverflow.com/questions/1441532/is-there-a-way-to-access-a-javascript-variable-using-a-string-that-contains-the) – Felix Kling Jan 20 '13 at 20:17
  • 2
    @JosephSilber Can you stop using w3fools as a reference, please. They are not. – Mr Lister Jan 20 '13 at 20:21
  • @FelixKling it's not a duplicate of that because the variable in this question is local, not global. – Alnitak Jan 20 '13 at 20:22
  • @MrLister - Of course they're not an actual reference. [MDN](https://developer.mozilla.org/en-US/) is, and should be used instead. – Joseph Silber Jan 20 '13 at 20:22
  • @Alnitak: The other question does not even mention global or local variables. And the accepted answer gives a solution for both. In any case, I don't expect this question to be closed as duplicate, but it's pretty much the same question. Although you have provided a much better solution for this particular scenario. – Felix Kling Jan 20 '13 at 20:29
  • @FelixKling actually the accepted answer on that other own only works for an _object_ variable - it won't work in this question's case. – Alnitak Jan 20 '13 at 20:33
  • @Alnitak: But isn't that the point? You cannot do it for local variables (apart from `eval`). – Felix Kling Jan 20 '13 at 20:49

5 Answers5

3

If (and only if) a variable (myVar) contains the name of a property of another object (myObj) you can use:

myObj[myVar]

to access that property.

In this case, your fruits array is just a normal local variable, so there's no way (short of the frowned-upon eval function) to access it indirectly.

You can of course use fruits.length to directly find its length.

A better solution would be a nested object of foods, and not an array:

var foods = {
    fruits: [ "Banana", "Orange", "Apple", "Mango" ],
    steak: [ ... ],
    pizza: [ ... ],
    bread: [ ... ]
};

at which point you can use the syntax above and write:

var myType = 'fruits';
var count = foods[myType].length;
Alnitak
  • 334,560
  • 70
  • 407
  • 495
2

Maybe what you want is

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var foods = ["steak","pizza","bread", fruits];

This way your code will work, since we have stored a reference to the array fruits inside the foods instead of the string "fruits".

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
  • this will work, but IMHO it's not a good solution. I'm pretty sure the OP wants to use the _string_ "fruits" to indirect into that array. – Alnitak Jan 20 '13 at 20:44
  • @Alnitak, i am sure using an object is the proper solution to such problems. My answer is a bit directly based on the `var y = foods[3];` part of the question.. – Gabriele Petrioli Jan 20 '13 at 20:47
2

You seem to have a huge misunderstanding of the difference between the variable identifier fruits and the string "fruits".

Let's describe your code together so you understand well what you are doing.


  • var fruits = ["Banana", "Orange", "Apple", "Mango"];

You have a variable named fruits which identifies an array of four elements, all strings. You could do the following with that array:

alert(fruits.length); // 4
alert(fruits[0]); // Banana
alert(fruits[3]); // Mango
alert(fruits); // Banana, Orange, Apple, Mango

  • var foods = ["steak","pizza","bread","fruits"];

You have a variable named foods which identifies an array of four elements, again: all strings. You could again do the following:

alert(foods.length); // 4
alert(foods[0]); // steak
alert(foods[3]); // fruits
alert(foods); // steak, pizza, bread, fruits

  • You try to count the fruits, doing foods[3].length

You should notice that when we did alert(fruits), it displayed Banana, Orange, Apple, Mango. And when we did alert(foods[3]), it displayed fruits. This should give you a hint: the array you named fruits and the string "fruits" are two different things!

That is why foods[3].length is 6, because the length of "fruits" is 6.


Solution

EDIT: Check Altiniak's answer. I leave the rest of my post for the long and valid explaination. The idea of using window was almost worse than using eval()...

snooze92
  • 4,178
  • 2
  • 29
  • 38
  • 1
    `fruits` is not a global variable so `window[foods[3]].length;` will not work. The OP's code is inside a function so nothing get store in the global scope.. – Gabriele Petrioli Jan 20 '13 at 20:35
  • My mistake. I will edit, but there is nothing to add to Alnitak's answer anymore ;) I would upvote his if I could :P – snooze92 Jan 20 '13 at 20:39
  • @snooze92 downvote removed - you're neutral now ;-) Why can't you upvote? – Alnitak Jan 20 '13 at 20:42
  • @Alnitak I created my StackOverflow account 2h ago, still missing 6 _"reputation points"_ until I can upvote :) – snooze92 Jan 20 '13 at 20:44
  • @snooze92 oh yeah, I forgot that new accounts can't even upvote :) – Alnitak Jan 20 '13 at 20:45
  • This worked for me. I'm sorry I forgot to mention that my other code is in a function, my mistake. Thanks for everyone's help:) – Dropoff510 Jan 20 '13 at 20:51
  • @Altinak I won some reputation points since my answer was chosen, you got your upvote. – snooze92 Jan 20 '13 at 20:55
  • @Dropoff510 Still, I don't think it is _"fair"_ to validate the answer who simply states "The good answer is someone else's!" I think you should accept Altinak's answer. ;) (and I hope he'd still keep my upvote :P) – snooze92 Jan 20 '13 at 20:56
1

In the following:

var y=foods[3];
x.innerHTML= y.length;"

You are assigning the 4th element in the foods array to the y variable, which is the string "fruits". If you want the length of the array, just do this:

x.innerHTML = foods.length;

EDIT: I am assuming you just want the length of the foods array and NOT to store the fruits array in the foods variable (if you need that, Gaby's answer can give you that)

Mathew Thompson
  • 55,877
  • 15
  • 127
  • 148
  • 1
    He actually wants to access the `fruits` array by using the `foods` array. – Amberlamps Jan 20 '13 at 20:15
  • @Amberlamps OP says "I get 6 which is the length of the word "fruit" but i want the length of the array fruit." – Mathew Thompson Jan 20 '13 at 20:16
  • 2
    @mattytommo: Exactly. `foods[3]` is the word `fruits` and he wants to access the variable with that name. I had to read it a couple of times until I understood what the OP wants. – Felix Kling Jan 20 '13 at 20:18
  • @mattytommo: I am pretty sure, that he wants what I described and also what Felix said. – Amberlamps Jan 20 '13 at 20:19
  • The OP _clearly_ wants to indirect from the _string_ "fruits" into the local array of the same name. – Alnitak Jan 20 '13 at 20:24
  • I wonder why people always suspect me giving downvotes only because I commented on their answer... it's sad. – Felix Kling Jan 20 '13 at 20:30
  • I don't think it's very *clear* what the OP wants. Downvoting this answer for giving a correct explanation to incorrect interpretation of an ambiguous question is a little unfair. – Paul Fleming Jan 20 '13 at 21:11
0

Hope I get what you want. You you have the word "fruits" and from that, you want to fetch the contents of the var named fruits, right?

That can be done using eval.

var fruitlen = eval('fruits').length;

Is this what you wanted?

Mr Lister
  • 45,515
  • 15
  • 108
  • 150