mojarras
mojarras

Reputation: 1634

How can I loop through this array in javascript?

I'm trying to loop through this array but it does not return any length. Is it possible?

Thanks!

<!DOCTYPE html>
<html>
  <body>
    <button onclick="myFunction()">click</button>
    <script>
      function myFunction()
      {
        var fruits = [];
        fruits["B"] = "Banana";
        fruits["A"] = "Apple";
        fruits["O"] = "Orange";

        delete fruits["A"];

        alert(fruits["A"]); // Alerts "undefined"
        alert(fruits["B"]); // Alerts "Banana"
        alert(fruits.length); // Alerts "0"
      }
    </script>

  </body>
</html>

Upvotes: 1

Views: 266

Answers (4)

bittersweetryan
bittersweetryan

Reputation: 3453

Looks like you want an object instead of an array so you can access an element by key:

var fruits = {
    a : 'apple',
    b : 'banana'
};

fruits.a //apple
fruits['b'] //banana

then you can loop through them by key:

for( var item in fruits ){
    fruits[ item ];
}

One thing to note is that this will loop through all keys in fruits AND any object it inherits from (in my example its only object.prototype). If you wanted to be careful you could use the hasOwnProperty method to make sure that the property exists on the fruits object and not any of its prototypes:

for( var item in fruits ){

    if( fruits.hasOwnProperty( item ) ){
        fruits[ item ];
    }
}

Upvotes: 2

Kashif Hanif
Kashif Hanif

Reputation: 1728

You can not declare array like this.you need to declare array using new keyword

var Fruit=new Array("Banana","Apple","Orange");

then you can access like this

 alert(Fruit[0]);//Banana
    alert(Fruit[1]);//Apple
    alert(Fruit[2]);/Orange

Hope this will work

Upvotes: 0

Default
Default

Reputation: 16518

What you are looking for is a JavaScript object. If you declare your fruits variable as an object literal, you can perform the actions that you desire.

var fruits = {};
fruits["B"] = "Banana"; // Can also do this as fruits.B = "Banana";
fruits["A"] = "Apple";
etc.

Then doing things like alert(fruits["A"]) will give you an alert message that says "Apple" as you desire. However, JavaScript objects do not have a length property, but you can do Object.keys(fruits) which will return an array of the keys of your fruits variable, and then you can access the length property of that.

Upvotes: 1

jbabey
jbabey

Reputation: 46657

Arrays can only have numeric indexes. When you write fruits["B"] = "Banana"; you're assigning a property to the object (Arrays are objects), not adding an item to the array.

You can either use an array properly with numeric indexes, or use an object with string keys instead:

var fruits = [];
fruits.push("Banana");
alert(fruits[0]); // "Banana"

var fruits = {};
fruits["B"] = "Banana";
alert(fruits["B"]); // "Banana"

If you need the length of the object, use Object.keys(fruits).length; Docs

Upvotes: 8

Related Questions