如何在 javascript
中检查 hashset
是否包含特定值?我已经尝试过以下方法,但不起作用:
if (hashset.contains(finalDate)) {
alert("inside if");
}
我的js代码:
$.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.
}
最佳答案
如果您指的哈希集是一个对象(或哈希...),那么您可以通过以下方式检查它是否包含 key :
var hash = { foo: 'bar', baz: 'foobar' };
'foo' in hash;
如果您寻找特定的值(value):
function containsValue(hash, value) {
for (var prop in hash) {
if (hash[prop] === value) {
return true;
}
return false;
}
}
如果您想做一些更“全局”的事情(我不推荐!),您可以更改对象的原型(prototype),例如:
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
关于javascript - 检查元素是否在哈希集中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13970814/