Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the length of a 'named' array? [duplicate]

Tags:

javascript

I'm not sure what they are called, but what I mean is this:

array["water"] = 50;
array["fire"] = 30;

length should be 2 here

how can I see how many attributes I have in the array? array.length doesn't work =( I've been trying all kinds of things and I feel like I'm missing something really simple here..

Thank you for your help

like image 743
Hate Names Avatar asked Aug 04 '13 18:08

Hate Names


People also ask

How do you find the length of an array array?

With the help of the length variable, we can obtain the size of the array. Examples: int size = arr[]. length; // length can be used // for int[], double[], String[] // to know the length of the arrays.

How do you find a repeated value in an array?

Duplicate elements can be found using two loops. The outer loop will iterate through the array from 0 to length of the array. The outer loop will select an element. The inner loop will be used to compare the selected element with the rest of the elements of the array.

How do you print the length of an array?

Use the len() method to return the length of an array (the number of elements in an array).

Does .length work on arrays?

The length variable is applicable to an array but not for string objects whereas the length() method is applicable for string objects but not for arrays.


1 Answers

You could use Object.keys() to obtain an array of keys, then count them:

Object.keys(array).length

Or, if you're targeting ECMAScript 3 or otherwise don't have Object.keys(), then you can count the keys manually:

var length = 0;
for (var key in array) {
    if (array.hasOwnProperty(key)) {
        ++length;
    }
}

There are a few edge cases with this approach though, depending on the browsers you're targeting, so using Mozilla's polyfill for Object.keys() instead might be a good idea.

like image 171
rid Avatar answered Oct 16 '22 15:10

rid