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?
If (and only if) a variable (
myVar) contains the name of a property of another object (myObj) you can use:to access that property.
In this case, your
fruitsarray is just a normal local variable, so there’s no way (short of the frowned-uponevalfunction) to access it indirectly.You can of course use
fruits.lengthto directly find its length.A better solution would be a nested object of foods, and not an array:
at which point you can use the syntax above and write: