javascript - 确保 JavaScript 中的条件始终为真

标签 javascript assert

在 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/

相关文章:

c++ - 验证器断言失败

python - 求解一对线性方程时的断言错误

c# - 单元测试的数据准备 - C#

Java断言 - 第二个参数评估?

常规 'assert' : How to display the value?

javascript - jQuery DataTable 中显示的总条目数错误

javascript - 在 JavaScript(和开发工具)中无法访问 Cookie,但会与 XHR 请求一起发送(不使用 httponly)

javascript - Sorttable.js(Javascript 表排序)在 javascript 中创建表时不起作用

javascript - 模拟外部依赖

javascript - 翻译从原型(prototype) de jquery 插入新元素