admin管理员组文章数量:1401650
I use a Javascript hash object to store a set of numerical counters, set up like this [this is greatly simplified]:
var myHash = {
A: 0,
B: 0,
C: 0
};
Is there a way to make other keys, ones not explicitly in myHash
, map to keys that are? For instance, I'd like [again, this is simplified]:
myHash['A_prime']++; // or myHash.A_prime++;
to be exactly equivalent to
myHash['A']++; // or myHash.A++;
e.g. incrementing the value found at the key A
, not A_prime
.
I use a Javascript hash object to store a set of numerical counters, set up like this [this is greatly simplified]:
var myHash = {
A: 0,
B: 0,
C: 0
};
Is there a way to make other keys, ones not explicitly in myHash
, map to keys that are? For instance, I'd like [again, this is simplified]:
myHash['A_prime']++; // or myHash.A_prime++;
to be exactly equivalent to
myHash['A']++; // or myHash.A++;
e.g. incrementing the value found at the key A
, not A_prime
.
5 Answers
Reset to default 2Assuming there aren't any valid string values in this hash, you could create your own mapping of keys to other keys, within the hash itself, and wrap the key/value pairs in your own function, as follows:
var hash = {
A: 0,
B: 0,
C: 0,
A_asdf: 'A',
B_asdf: 'B',
A_another: 'A'
}
function increment(key)
{
// iteratively find the real key
while (typeof(hash[key]) == 'string')
{
key = hash[key];
}
hash[key]++;
}
A way of solving this would be wrapping all values in an object, and use this object in several keys.
var myHash = {
A: {value: 0},
...
};
myHash['A_prime'] = myHash['A'];
myHash['A_prime'].value++;
I think you would be better off just writing a function to acplish the incrementation of one hash array or multiple depending on what you are trying to acplish. I may have not understood the question correctly but this is my solution.
var smallHash = {
A: 0,
B: 0,
C: 0,
A_prime:'A',
B_prime:'B',
C_prime:'C'
};
function incrementPrime(myHash,key)
{
letterKey = myHash[key];
myHash[letterKey]++;
}
incrementPrime(smallHash,'C_prime');
alert("C is now: "+smallHash['C']); // should return 1
You could act on the key, instead of the hash:
var myHash = {
A: 0,
B: 0,
C: 0
};
function incr(prop){
myHash[prop[0]]++;
}
incr('A');
incr('A_asdf');
The function incr
could be anything else you want to apply to the hash.
As described, no. If you can change your keys to objects though you'd get closer:
var x = new Object();
var y = x;
myHash[x] = 1;
myHash[y]++; // should increment the value since y is x.
本文标签: Mapping multiple keys to the same value in a Javascript hashStack Overflow
版权声明:本文标题:Mapping multiple keys to the same value in a Javascript hash - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744277548a2598488.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论