JavaScript array length method

Can someone explain why the second warning says 0?

var pollData = new Array(); pollData['pollType'] = 2; alert(pollData['pollType']); // This prints 2 alert(pollData.length); // This prints 0 ?? 
+4
source share
6 answers

The length of the array changes only when adding numeric indices. For instance,

 pollData["randomString"] = 23; 

does not affect the length but

 var pollData = []; pollData["45"] = "Hello"; pollData.length; // 46 

changes the length to 46. Note that it does not matter if the key was a number or a string if it is a numeric integer.

In addition, you should not use arrays in this way. Consider this more likely a side effect, since arrays are also objects, and in JavaScript any object can contain arbitrary keys as strings.

+8
source

Because you haven't added anything to the array yet. You have assigned only the dynamically generated pollType attribute to an array object.

If you use numeric indices, then the array automatically processes the length. For instance:

 var arr = [ ]; // same as new Array() arr[2] = 'Banana!'; alert(arr.length); // prints 3 (indexes 0 through 2 were created) 
+2
source

The length property takes into account only those elements of the array whose names are indexes (for example, '1' , '2' , '3' , ...).

0
source

Arrays in JavaScript have only numeric indices.

Use an object, which is essentially what you do above by setting properties for this array object.

0
source

array.length returns the number of values โ€‹โ€‹stored in the array. The first warning returns the value "pollType".

The reference guide I always use when you need help with javascript arrays is the page http://www.hunlock.com/blogs/Mastering_Javascript_Arrays

I would also read what it says under the heading Javascript does not support associative arrays, as you may run into problems with this too.

0
source

var pollData = Array ();

 function test() { pollData[0] = 2 alert(pollData[0]); alert(pollData.length); } 

// [x] - position of the array; therefore ['polltype'] causes problems

0
source

Source: https://habr.com/ru/post/1344028/


All Articles