在 JavaScript 中,是否可以测试某个条件在程序的整个执行过程中是否保持为真?在这里,我想确保变量 a 从程序开始到结束始终能被 3 整除。
//Assert that the following is always true, and print an error message if not true
ensureAlwaysTrue(a % 3 == 0); //print an error message if a is not divisible by 0
//from this point onward
a = 6;
a = 10 //print error message, since a % 3 != 0
function ensureAlwaysTrue(){
//this is the function that I'm trying to implement.
}
一种解决方案是在每个变量赋值后添加语句来检查断言,但这会是多余且麻烦的。有没有更简洁的方法来检查程序执行过程中条件是否为真?
最佳答案
哇,这些都是可怕的解决方案。如果您确实想这样做,您可以创建一个模型并使用模型上的方法访问该值。这是一个例子:
function Model(value){
this.value = value;
}
Model.prototype = {
get: function(){
return this.value;
},
set: function(value){
if(this.validate(value)){
this.value = value;
return this;
}
throw Error('Not a valid value.');
},
test: function(func){
this.validate = func;
return this;
}
};
var a = new Model();
a.test(function(val){ return val == 7 });
// Sets value of a to 7
a.set(7);
// Gets value of a (7 in this case)
a.get();
// Throws an error
a.set(5);
关于javascript - 确保 JavaScript 中的条件始终为真,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14533987/