您好,欢迎来到华佗养生网。
搜索
您的当前位置:首页JavaScript中的console.assert()函数介绍_javascript技巧

JavaScript中的console.assert()函数介绍_javascript技巧

来源:华佗养生网
 在JavaScript程序的开发和维护过程中,Assert(断言)是一个很好的用于保证程序正确性的特性。在具备调试工具的浏览器上,这一特性可以通过调用console.assert()来实现。比如在以下代码中,console.assert()语句保证cat对象的score变量值长度为3:
代码如下:
function cat(name, age, score){
this.name = name;
this.age = age;
this.score = score;
}
var c = new cat("miao", 2, [6,8,7]);
console.assert(c.score.length==3, "Assertion of score length failed");

在console.assert()语句中,第一个参数为需要进行assert的结果,正常情况下应当为true;第二个参数则为出错时在控制台上打印的错误信息。比如,当上述例子中score变量的数组长度不为3时:
代码如下:
function cat(name, age, score){
this.name = name;
this.age = age;
this.score = score;
}
var c = new cat("miao", 2, [6,8]);
console.assert(c.score.length==3, "Assertion of score length failed");


代码执行后,Firebug控制台将会打印错误信息:

浏览器支持

console.assert()在有调试工具的浏览器上支持较好,各大浏览器均支持此功能。不过值得一提的是,Firefox自身并不支持此功能,在Firefox上必须安装Firebug插件才能使用console.assert()。

Copyright © 2019- huatuo7.cn 版权所有 湘ICP备2022005869号-9

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务