Should negative indices in JavaScript arrays contribute to the length of the array?

In javascript, I define an array like this

var arr = [1,2,3]; 

also i can do

 arr[-1] = 4; 

Now if i do

 arr = undefined; 

I also lose the reference to the value in arr [-1] .

SO logically seems to me that arr [-1] is also part of arr .

But when I do the following (without setting arr to undefined)

 arr.length; 

It returns 3 not 4 ;

So my point is , if arrays can be used with negative indices, these negative indices should also be part of their length **. I donโ€™t know, maybe Iโ€™m wrong, or I may miss the concept of arrays.

+68
javascript arrays
Nov 29
source share
8 answers

So it logically seems to me that arr [-1] is also part of arr.

Yes, it is, but not in the way you think.

You can assign arbitrary properties to an array (like any other object in JavaScript), which is what you do when you โ€œindexโ€ the array to -1 and assign a value. Since this is not an element of an array, but simply an arbitrary property, one should not expect length to take this property into account.

In other words, the following code does the same:

 โ€‹var arr = [1, 2, 3]; โ€‹arr.cookies = 4; alert(arr.length) // 3; 
+81
Nov 29 '12 at 4:01
source share

The length property will return number one above the highest assigned "index", where the "indexes" of Array are integers greater than or equal to zero. Note that JS allows for sparse arrays:

 var someArray = []; someArray[10] = "whatever"; console.log(someArray.length); // "11" 

Of course, if there are no elements, then length is 0 . Also note that length not updated if you use delete to delete the highest element.

But arrays are objects, so you can assign properties with other arbitrary property names, including negative numbers or fractions:

 someArray[-1] = "A property"; someArray[3.1415] = "Vaguely Pi"; someArray["test"] = "Whatever"; 

Note that behind the scenes, JS converts property names to strings, even when you specify a number like -1 . (Positive integer indices also become strings, for that matter.)

Massive methods such as .pop() , .slice() , etc., work only with zero or higher integer "indices", and not with other properties, so length is consistent at this point.

+20
Nov 29
source share

Note that when you use the position index (or 0), the values โ€‹โ€‹are placed inside the array:

 var array = []; array[0] = "Foo"; array[1] = "Bar"; // Result: ["Foo", "Bar"] // Length: 2 

This is not the case when you add non-index values โ€‹โ€‹(not 0-9 +):

 var array = []; array[0] = "Foo"; array[1] = "Bar"; array[-1] = "Fizzbuzz"; // Not a proper array index - kill it // Result: ["Foo", "Bar"] // Length: 2 

Values โ€‹โ€‹are only placed in an array when you play by the rules. When you do not, they will not be accepted. However, they are accepted on an Array object, which is the case with almost anything in JavaScript. Even if ["Foo", "Bar"] are the only values โ€‹โ€‹in our array, we can still access "Fizzbuzz" :

 array[-1]; // "Fizzbuzz" 

But note that this is not part of the array values, since its "index" is not valid. Instead, it was added to the array as another member. We could access the other elements of the array in the same way:

 array["pop"]; // function pop() { [native code] } 

Note that we are accessing the pop method in an array that tells us that it contains native code. We do not refer to any of the values โ€‹โ€‹of the array with the key "pop", but rather to the element of the array object. We can confirm this again by clicking on the public elements of the object:

 for (var prop in array) console.log(prop, array[prop]); 

From which the following follows:

  0 Foo 1 Bar -1 Fizzbuzz 

So again, this is on an object, but it is not in an array.

Awesome question! Thought I should do a double trick.

+6
Nov 29 '12 at 4:16
source share

If you really want negative indices and other indices to be included in length, create yourself:

 function getExtendedArray() { var a = []; Object.defineProperty(a, 'totalLength', { get : function() { return Object.keys(a).length; } }); return a; } 

Then, for example:

 var myArray = getExtendedArray(); console.log(myArray.totalLength); // 0 myArray.push("asdf"); myArray[-2] = "some string"; myArray[1.7777] = "other string"; console.log(myArray.totalLength); // 3 
+5
Jul 18 '13 at 16:22
source share

Arrays in JavaScript are actually objects. They are simply prototyped from the Array constructor.

Array indices are actually keys in the hash map, and all keys are converted to strings. You can create any key (ie "-1"), but the methods on Array are designed to work as an array. Thus, length is not the size of an object; it is more likely to be guaranteed to be larger than the largest integer index. Similarly, printing arr will only display values โ€‹โ€‹with integer keys> = 0.

More info here

+3
Nov 29 '12 at 4:05
source share

According to MDN:

The value of the length property is a positive integer and less than 2 for 32 powers (232)

In Javascript, you can set a property for any object that you create.

 var array = new Array(); array = [1,2,3]; array["boom"] = "pow"; 

In the same way, when you set a negative index, it stores it as a property in the array, not part of the index.

 array[-1] = "property does not add to array length"; 

This is why the length does not reflect it, but the for..in loop shows it.

+1
Nov 29 '12 at 4:25
source share

An array is just a special kind of object in JS. There is a special syntax that is good because it allows us to work effectively with them. Imagine how tiring it would be to write an array of letters this way:

 const array = {{0: 'foo'}, {1: 'bar'}, {2: 'baz}} //etc... 

But there are still objects. So if you do:

 const myArray = [42, 'foo', 'bar', 'baz']; myArray[-1] = 'I am not here'; myArray['whatever'] = 'Hello World'; 

These non-integer properties will be attached to the object (which is an array), but they are not available to native methods such as Array.length .

You can assume that the native 'length' method is a getter method that counts all properties (and indexes are properties, and values โ€‹โ€‹are actual values) that can be converted to a positive integer or zero. Something like this pseudo implementation:

 const myArray = { '-1': 'I am not here', // I have to use apostrophes to avoid syntax error 0: 42, 1: 'foo', 2: 'bar', 3: 'baz', whatever: 'Hello World', myLength() { let counter = 0; for (let prop in this) { let toInt = parseInt(prop, 10); if (!Number.isNaN(toInt) && toInt > -1) { // If you're not an integer, that not your business! Back off! counter += 1; } } return counter; } } console.log(myArray.myLength()); // 4 
+1
Nov 05 '18 at 11:36
source share

When using non-positive or non-numeric indexes, an array behaves like an associative array that has key-value pairs.

To iterate through an array, you can use

 for(var index in myArray) { document.write( index + " : " + myArray[index] + "<br />"); } 
0
Nov 29
source share



All Articles