简体   繁体   中英

How to get the correct array length

In my code i initialize array then put a value inside it why the output be 0 ?in spite of this should be 1

       var changedfields=[];
       changedfields['product']="productname";
       alert(changedfields.length);

You're creating an associative array (normal arrays have an numeric index) but are actually trying to build a HashMap (a key, value pair). Use Objects or ES6 Maps .

I hope the following example will help you out:

var changedfields = {}; // create an object
changedfields['product']="productname";
var keys = Object.keys(changedfields);  // returns the keys of the object ['product']
alert(keys.length);

I would suggest to read more about datastructures in javascript and avoid associative arrays in general.

Your question is interesting. Following is the answer.

First of all Arrays in Javascript are object type.

The first line you wrote creates an empty array and it's type is object.

var changedfields=[];

The second line you wrote creates a property called product of changedfields and sets the value to productname . It allows you add the product property because Javascript Array type is object. If you just had var changedfields; you could not add this property.

changedfields['product']="productname";

The third line you wrote simply finds the length of the empty array.

alert(changedfields.length);

In Javascript associative arrays are achieved using object. But if you want to add the product name in changedfields array. You could use push method like below and check the length:

changedfields.push('productname');
console.log(changedfields.length);

Javascript numerical indexed array length
So the Javascript numerical indexed array length can be calculated this way:

console.log(array.length);
console.log(changedfields.length); // in your case 

The Javascript associative array length
The Javascript associative array (object) length can be calculated following ways:
Option 1:

Object.len = function(obj) {
var objLen = 0;
for (i in obj) {
   obj.hasOwnProperty(i) ? objLen++ : '';
}
return objLen;
};
console.log(Object.len(changedfields));

Option 2:

console.log(Object.keys(array).length);
console.log(Object.keys(changedfields).length); // in your case

Note: This has issues with Internet Explorer 8, Opera etc

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