2

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.
}
4

1 回答 1

3

如果您指的哈希集是一个对象(或哈希...),那么您可以通过以下方式检查它是否包含键:

var hash = { foo: 'bar', baz: 'foobar' };
'foo' in hash;

如果您寻找特定的价值:

function containsValue(hash, value) {
    for (var prop in hash) {
        if (hash[prop] === value) {
            return true;
        }
        return false;
    }
}

如果你想做一些更“全局”的事情(我不推荐!)你可以改变 Object 的原型,比如:

Object.prototype.containsValue = function (value) {
    for (var prop in this) {
        if (this[prop] === value) {
            return true;
        }
    }
    return false;
}

在这种情况下:

var test = { foo: 'bar' };
test.containsValue('bar'); //true
test.containsValue('foobar'); //false
于 2012-12-20T11:15:42.740 回答