How to use an array as a key in javascript?

I have a simple python example:

programs = {}
if not programs.has_key(( program, time )):
     programs[( program, time )] = 0
programs[( program, time )] = programs[( program, time )] + 1

How to use an array as a key in javascript?

+5
source share
3 answers

Will this be a trick for you?

jsfiddle

<script>
var ary = {person1:'valerie', person2:'alex'};
for (key in ary) {
    document.write(key, '<br>')
}

document.write(ary['person2'], '<br>')
</script>
+3
source

It will "work". (but I do not recommend it)

var a = {};
var b = [1,2,3];    
a[b] = 'hello';

// a[b] evaluates to 'hello'
// a[[1,2,3]] evaluates to 'hello'
// a['1,2,3'] evaluates to 'hello'

This works because when you pass an array [1,2,3] as a hash (map / associative array), the hash is converted to the string "1,2,3" before converting the hash. It should suit your needs if you do not need two different arrays of the same value to display different hash values.

var c = [1,2,3]
// a[c] evaluates to 'hello' even though we never executed a[c] = 'hello'
// but b == c evaluates to false
// b & c are two separate objects with the same values, so when they
// get converted to a string for hashing, they return the same value from the hash

As already mentioned, you will need more than the standard JavaScript hash if you want to use object references as your keys.

Update

@speedplane:

, JS toString() , -. , , :

 ["x", "y", "z"].toString;                // 'x,y,z'
 ["x,y,z"].toString();                    // 'x,y,z'
 [1,2,3].toString();                      // '1,2,3'
 [1,2,'3'].toString();                    // '1,2,3'
 [[1],[2],[3]].toString();                // '1,2,3'
 [["x",1], ["y",2], ["z",3]].toString();  // 'x,1,y,2,z,3'

, , , . .

+16

JavaScript keys are strings.

You need WeakMapeither a custom method to map arrays to other objects.

+8
source

All Articles