什么是JavaScript中的“断言”? [英] What is “assert” in JavaScript?
问题描述
断言
在JavaScript中是什么意思?
What does assert
mean in JavaScript?
我见过类似的内容:
assert(function1() && function2() && function3(), "some text");
想知道方法 assert()
确实。
推荐答案
JavaScript中没有断言
(然而,有谈论添加一个,但它还处于早期阶段)。也许你正在使用一些提供一个库的库。通常的意思是如果传递给函数的表达式为false则抛出错误;这是断言检查的一般概念的一部分。通常断言(因为它们被称为)仅用于测试或调试构建并从生产代码中删除。
There is no assert
in JavaScript (yet; there's talk of adding one, but it's at an early stage). Perhaps you're using some library that provides one. The usual meaning is to throw an error if the expression passed into the function is false; this is part of the general concept of assertion checking. Usually assertions (as they're called) are used only in "testing" or "debug" builds and stripped out of production code.
假设您有一个函数是应该总是接受一个字符串。你想知道是否有人用不是字符串的东西调用了那个函数。所以你可以这样做:
Suppose you had a function that was supposed to always accept a string. You'd want to know if someone called that function with something that wasn't a string. So you might do:
assert(typeof argumentName === "string");
...其中断言
会抛出如果条件为假则出错。
...where assert
would throw an error if the condition were false.
一个非常简单的版本如下所示:
A very simple version would look like this:
function assert(condition, message) {
if (!condition) {
throw message || "Assertion failed";
}
}
更好的是,利用错误
对象,如果JavaScript引擎支持它(真的可能没有),它具有收集堆栈跟踪等优点:
Better yet, make use of the Error
object if the JavaScript engine supports it (really old ones might not), which has the advantage of collecting a stack trace and such:
function assert(condition, message) {
if (!condition) {
message = message || "Assertion failed";
if (typeof Error !== "undefined") {
throw new Error(message);
}
throw message; // Fallback
}
}
即使IE8已经错误
(虽然它没有 stack
属性,但现代引擎[包括现代IE]确实如此)。
Even IE8 has Error
(although it doesn't have the stack
property, but modern engines [including modern IE] do).
这篇关于什么是JavaScript中的“断言”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!