如何检查所有对象键是否都具有假值 [英] how to check if all object keys has false values
本文介绍了如何检查所有对象键是否都具有假值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
JS对象:
var saver = {
title: false,
preview: false,
body: false,
bottom: false,
locale: false
};
问题是如何检查所有值是否都是 false ?
The question is how to check if all values is false?
我可以使用$ .each()jQuery函数和一些标志变量,但是可能有更好的解决方案?
I can use $.each() jQuery function and some flag variable, but there may be a better solution?
推荐答案
这可以解决问题...
This will do the trick...
var result = true;
for (var i in saver) {
if (saver[i] === true) {
result = false;
break;
}
}
您可以通过索引或键(如上所述)使用循环来迭代对象.
You can iterate objects using a loop, either by index or key (as above).
如果您使用的是整洁的代码,并且不重复,则只需将其放入函数中即可.
If you're after tidy code, and not repeating that then simply put it in a function...
Object.prototype.allFalse = function() {
for (var i in this) {
if (this[i] === true) return false;
}
return true;
}
然后您可以在需要时调用它,就像这样...
Then you can call it whenever you need, like this...
alert(saver.allFalse());
这是一个有效的示例...
Here's a working sample...
Object.prototype.allFalse = function() {
for (var i in this) {
if (this[i] === true) return false;
}
return true;
}
var saver = {
title: false,
preview: false,
body: false,
bottom: false,
locale: false
};
console.log("all are false - should alert 'true'");
console.log(saver.allFalse());
saver.body = true;
console.log("one is now true - should alert 'false'");
console.log(saver.allFalse());
这篇关于如何检查所有对象键是否都具有假值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文