Reputation: 81
How can I check whether a hashset
contains a particular value or not in javascript
? I have tried the following which is not working:
if (hashset.contains(finalDate)) {
alert("inside if");
}
My js code:
$.each(cdata.lines, function(idx, line){
// line.hashsetvariable is my hashset which contain all dates and
// let finaldate is 2012-19-12
// I want to check this date in my hashset.
}
Upvotes: 2
Views: 5203
Reputation: 25682
If the hash set you mean is an object (or hash...) then you can check whether it contains a key by:
var hash = { foo: 'bar', baz: 'foobar' };
'foo' in hash;
If you look for particular value:
function containsValue(hash, value) {
for (var prop in hash) {
if (hash[prop] === value) {
return true;
}
return false;
}
}
If you want to do something more "global" (I don't recommend!) you can change Object's prototype like:
Object.prototype.containsValue = function (value) {
for (var prop in this) {
if (this[prop] === value) {
return true;
}
}
return false;
}
In this case:
var test = { foo: 'bar' };
test.containsValue('bar'); //true
test.containsValue('foobar'); //false
Upvotes: 3