我有这段代码:
var obj = {
eins : false,
zwei : false,
drei : false
};
$.each(obj, function (k, v) {
if (!v) {
console.log(false);
}
});
现在我要做的是以下内容:检查obj中的所有值是否都为真。如果他们这样做,如果他们不这样做,请再试一次。
我试过搞乱setInterval和$ .each但是无法让它同步运行..
答案 0 :(得分:2)
简单循环以查看对象是否全部为真,并且只需要if / else来确定步骤。
var obj = {
eins : false,
zwei : false,
drei : false
};
//function to call to see if code is updated
function check () {
//Check to see that every property in the object is true
var isValid = Object.keys(obj).every( function (key) {
return obj[key];
});
//if true, do what you need to do
if(isValid) {
document.body.style.backgroundColor = "green";
} else { //not true, than run check again
window.setTimeout(check, 500); //next check is half a second
}
}
check(); //initialize the checking
//A way to flip the data for the demo
document.querySelector("button").addEventListener("click", function () {
obj = {
eins : true,
zwei : true,
drei : true
};
});

<button>Set</button>
&#13;
答案 1 :(得分:1)
您可以使用Array.prototype.every
方法:
var allTrue = Object.keys(obj).every(function(key) {
return obj[key] === true;
});
答案 2 :(得分:0)
您根本不需要使用$ .each()。 for(... in ...)在以预定义的间隔调用的函数内工作得很好。
m := make(map[string]string)
err := json.Unmarshal(input, &m)
如果您需要在检查后检索值,请查看Promise类:)
答案 3 :(得分:0)
刚刚创建了一个关于你正在尝试的简单演示..
var obj = {
eins: false,
zwei: false,
drei: false
};
var doStuffTimer = setInterval(function() {
$.each(obj, function(k, v) {
if (!v) {
$('#logger').append('<p>obj.eins = ' + obj.eins + ' obj.zwei = ' + obj.zwei + ' obj.drei = ' + obj.drei + '</p>');
}
});
$('#logger').append("<p>--------------</p>");
}, 3000), //check every 3 seconds
flagTimer = setInterval(function() { /* below timer is for demo purpose only */
if (!obj.eins) {
obj.eins = true;
} else if (!obj.zwei) {
obj.zwei = true;
} else if (!obj.drei) {
obj.drei = true;
} else {
$('#logger').append('<p>Final Result: obj.eins = ' + obj.eins + ' obj.zwei = ' + obj.zwei + ' obj.drei = ' + obj.drei + '</p>');
clearInterval(flagTimer);
clearInterval(doStuffTimer); //clear the doStuffTimer; we dont want to keep the timer running
}
}, 5000); //change the flag every 5 seconds.. just for demo purpose
&#13;
p {
margin: 2px;
padding: 0;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="logger"></div>
&#13;
答案 4 :(得分:0)
这是另一种方法:
var obj = {
eins : false,
zwei : false,
drei : false
};
function allTrue (obj){
var all_true = true;
Object.keys(obj).forEach(function(key){
if(obj[key] === false) all_true = false;
});
return all_true;
}
function doSomething (){
// Do something
var key_;
Object.keys(obj).forEach(function(key){
if(obj[key] === false){
key_ = key;
}
});
obj[key_] = true;
console.log('iteration');
if(!allTrue(obj)) doSomething();
}
doSomething();
&#13;