JavaScript中的console.assert()函数介绍
作者:bea
在JavaScript程序的开发和维护过程中,Assert(断言)是一个很好的用于保证程序正确性的特性。在具备调试工具的浏览器上,这一特性可以通过调用console.assert()来实现。比如在以下代码中,console.assert()语句保证cat对象的score变量值长度为3: 代码如下: function cat(name, age, score){ this.name = name; this.age = age; this.score = sc
在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()。
有用 | 无用
代码如下:
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()。
有用 | 无用
猜你喜欢
您可能感兴趣的文章:
- JavaScript中的类(Class)详细介绍
- JavaScript实现防止网页被嵌入Frame框架的代码分享
- jQuery实现ichat在线客服插件
- jQuery中用dom操作替代正则表达式
- jQuery中:animated选择器用法实例
- 纯JavaScript实现获取onclick、onchange等事件的值
- JavaScript实现列出数组中最长的连续数
- jQuery中document与window以及load与ready 区别详解
- jQuery中:header选择器用法实例
- JavaScript实现查找字符串中第一个不重复的字符
- 基于jQuery的JavaScript模版引擎JsRender使用指南
- JavaScript中的数学运算介绍
- jQuery中:lt选择器用法实例
- JavaScript中的数值范围介绍
- JavaScript常用小技巧小结
- jQuery中:gt选择器用法实例
- 在浏览器中实现图片粘贴的jQuery插件-- pasteimg使用指南
- JavaScript中的值类型详细介绍
- JavaScript不使用prototype和new实现继承机制