简体   繁体   中英

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>

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

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 ];
    }
}

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM