首页  >  文章  >  web前端  >  JavaScript中的console.assert()函数介绍

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

高洛峰
高洛峰原创
2017-02-03 14:31:471620浏览

在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控制台将会打印错误信息:

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

浏览器支持

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

更多JavaScript中的console.assert()函数介绍相关文章请关注PHP中文网!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn