I have a simple example on python:
programs = {} if not programs.has_key(( program, time )): programs[( program, time )] = 0 programs[( program, time )] = programs[( program, time )] + 1
How to use array as key in Javascript ?
To use an array as object keys in JavaScript, we can convert the array to a string. to create the key array. Then we convert it to a string with JSON. stringify so we can use it as a property key.
JavaScript Array keys()The keys() method returns an Array Iterator object with the keys of an array. The keys() method does not change the original array.
For getting all of the keys of an Object you can use Object. keys() . Object. keys() takes an object as an argument and returns an array of all the keys.
JavaScript Array keys()The keys() method returns a new Array Iterator object that contains the keys for each element in the array.
This will "work". (but I don't 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'
It works because when you pass the array [1,2,3] as the hash (map/associative-array) key, is being converted to the string '1,2,3' before performing the hash lookup. It should suit your needs as long as you don't need two different arrays of the same value to map to 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 it was mentioned, you'll need more than the standard JavaScript hash if you want to use object references as your keys.
Based on the comment from @speedplane:
I suspect that JS calls toString()
on the array when you pass it into a hash key. So you can easily test what you're actually going to get as your key:
["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'
So again, I recommend that you don't do this unless you really understand what is going on. And even then, I wouldn't do it.
JavaScript keys are strings.
You need a WeakMap
, or a custom method to map arrays to other objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With