Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strings as keys of array

When using strings as keys of an array, console is showing that the array without these declared values and while iterating by this values where keys are string aren't displayed? , although i can get value of them.

>> var arr = [ 0, 1, 2, 3 ];    undefined  >> arr["something"] = "aught";    "aught"  >> arr    [0, 1, 2, 3]  >> arr["something"]    "aught"  >> for( var i = arr.length; i--; console.log( arr[ i ] ) );    3    2    1    0 

I understand that arrays are objects which has implemented some kind of 'enumerate' interface in JavaScript's engine.

Most interesting is that interpreter isn't throwing either warning or error, so I spent some time of searching for where data could be lost.

like image 449
abuduba Avatar asked Dec 25 '11 16:12

abuduba


People also ask

Can string be used as array?

Answer: Yes. Just like arrays can hold other data types like char, int, float, arrays can also hold strings. In this case, the array becomes an array of 'array of characters' as the string can be viewed as a sequence or array of characters.

What is an array key?

The array_keys() function is used to get all the keys or a subset of the keys of an array. Version: (PHP 4 and above) Syntax: array_keys(input_array, search_key_value, strict) Note: If the optional search_key_value is specified, then only the keys for that value are returned.

Can array key be an array?

As array values can be other arrays, trees and multidimensional arrays are also possible. And : The key can either be an integer or a string. The value can be of any type.


2 Answers

In javascript there are 2 type of arrays: standard arrays and associative arrays

  • [ ] - standard array - 0 based integer indexes only
  • { } - associative array - javascript objects where keys can be any strings

So when you define:

var arr = [ 0, 1, 2, 3 ]; 

you are defining a standard array where indexes can only be integers. When you do arr["something"] since something (which is what you use as index) is not an integer you are basically defining a property to the arr object (everything is object in javascript). But you are not adding an element to the standard array.

like image 164
Darin Dimitrov Avatar answered Sep 18 '22 09:09

Darin Dimitrov


for( var i = arr.length; i--; console.log( arr[ i ] ) );

This will only give you the numeric indices, of course, but you can still loop over both numeric indices and string keys of your array like this:

for (var x in arr) {     console.log(x + ": " + arr[x]); } /* (console output):      0: 0      1: 1      2: 2      3: 3      something: aught */ 
like image 25
fanaugen Avatar answered Sep 21 '22 09:09

fanaugen