JavaScript 中的“断言”是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15313418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is “assert” in JavaScript?
提问by frrlod
What does assert
mean in JavaScript?
assert
在 JavaScript中是什么意思?
I've seen something like:
我见过类似的东西:
assert(function1() && function2() && function3(), "some text");
And would like to know what the method assert()
does.
并想知道该方法的assert()
作用。
回答by T.J. Crowder
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.
assert
JavaScript中没有(然而;有谈论添加一个,但它处于早期阶段)。也许你正在使用一些提供一个的库。通常的意思是如果传入函数的表达式为false则抛出错误;这是断言检查的一般概念的一部分。通常断言(正如他们所说的那样)仅用于“测试”或“调试”构建并从生产代码中剥离出来。
Suppose you had a function that was supposed to alwaysaccept 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.
...assert
如果条件为假,哪里会抛出错误。
A very simple version would look like this:
一个非常简单的版本如下所示:
function assert(condition, message) {
if (!condition) {
throw message || "Assertion failed";
}
}
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:
更好的是,Error
如果 JavaScript 引擎支持该对象(非常老的可能不支持),请使用该对象,它具有收集堆栈跟踪等的优点:
function assert(condition, message) {
if (!condition) {
message = message || "Assertion failed";
if (typeof Error !== "undefined") {
throw new Error(message);
}
throw message; // Fallback
}
}
Even IE8 has Error
(although it doesn't have the stack
property, but modern engines [including modern IE] do).
甚至 IE8 也有Error
(虽然它没有这个stack
属性,但现代引擎 [包括现代 IE] 有)。
回答by joaoprib
If using a modern browser or nodejs, you can use console.assert(expression, object)
.
如果使用现代浏览器或 nodejs,您可以使用console.assert(expression, object)
.
For more information:
想要查询更多的信息:
回答by iX3
The other answers are good: there isn't an assert function built into ECMAScript5 (e.g. JavaScript that works basically everywhere) but some browsers give it to you or have add-ons that provide that functionality. While it's probably best to use a well-established / popular / maintained library for this, for academic purposes a "poor man's assert" function might look something like this:
其他答案很好:ECMAScript5 中没有内置断言函数(例如,基本上可以在任何地方使用的 JavaScript),但有些浏览器会提供给您,或者具有提供该功能的附加组件。虽然最好为此使用完善/流行/维护的库,但出于学术目的,“穷人的断言”功能可能如下所示:
const assert = function(condition, message) {
if (!condition)
throw Error('Assert failed: ' + (message || ''));
};
assert(1 === 1); // Executes without problem
assert(false, 'Expected true');
// Yields 'Error: Assert failed: Expected true' in console
回答by Crayon Violent
assert()
is not a native javascript function. It is a custom function someone made. You will have to look for it on your page or in your files and post it for anybody to help determine what it's doing.
assert()
不是原生的 javascript 函数。这是某人制作的自定义功能。您必须在您的页面或文件中查找它并将其发布给任何人以帮助确定它在做什么。
回答by Amrendra
检查这个:http: //net.tutsplus.com/tutorials/javascript-ajax/quick-tip-quick-and-easy-javascript-testing-with-assert/
it is for testing JavaScript. Amazingly, at barely five or six lines, this code provides a great level of power and control over your code, when testing.
它用于测试 JavaScript。令人惊讶的是,这段代码只有五六行,在测试时提供了强大的功能和对代码的控制。
The assert function accepts two parameters:
assert 函数接受两个参数:
outcome: A boolean, which references whether your test passed or failed
结果:一个布尔值,它引用您的测试是通过还是失败
description: A short description of your test.
描述:测试的简短描述。
The assert function then simply creates a list item, applies a class of either “pass” or “fail,” dependent upon whether your test returned true or false, and then appends the description to the list item. Finally, that block of coded is added to the page. It's crazy simple, but works perfectly.
然后 assert 函数简单地创建一个列表项,应用“通过”或“失败”的类,具体取决于您的测试返回的是真还是假,然后将描述附加到列表项。最后,该编码块被添加到页面中。这非常简单,但效果很好。
回答by joshpierro
Here is a really simple implementation of an assert function. It takes a value and a description of what you are testing.
这是断言函数的一个非常简单的实现。它需要一个值和您正在测试的内容的描述。
function assert(value, description) {
var result = value ? "pass" : "fail";
console.log(result + ' - ' + description);
};
If the value evaluates to true it passes.
如果该值计算为真,则通过。
assert (1===1, 'testing if 1=1');
If it returns false it fails.
如果它返回 false 则失败。
assert (1===2, 'testing if 1=1');
回答by Crazy Cat
If the assertion is false, the message is displayed. Specifically, if the first argument is false, the second argument (the string message) will be be logged in the developer tools console. If the first argument is true, basically nothing happens. A simple example – I'm using Google Developer Tools:
如果断言为假,则显示消息。具体来说,如果第一个参数为 false,则第二个参数(字符串消息)将被记录在开发人员工具控制台中。如果第一个参数为真,则基本上什么都不会发生。一个简单的例子——我正在使用谷歌开发者工具:
var isTrue = true;
var isFalse = false;
console.assert(isTrue, 'Equals true so will NOT log to the console.');
console.assert(isFalse, 'Equals false so WILL log to the console.');
回答by Matt Browne
It probably came with a testing library that some of your code is using. Here's an example of one (chances are it's not the same library as your code is using, but it shows the general idea):
它可能带有您的某些代码正在使用的测试库。这是一个示例(可能它与您的代码使用的库不同,但它显示了总体思路):
回答by Pavel
Word or function "assert" is mostly used in testing parts of application.
词或函数“assert”主要用于测试应用程序的部分。
Assert functions are a short way of instructing the program to check the condition (also called "assertion") and if the condition is not True, it will throw error.
断言函数是指示程序检查条件(也称为“断言”)的一种简短方法,如果条件不为真,则会抛出错误。
So let's see how it would look like in "normal code"
那么让我们看看它在“普通代码”中的样子
if (typeof "string" === "array") {
throw Error('Error: "string" !== "array"');
}
if (typeof "string" === "array") {
throw Error('Error: "string" !== "array"');
}
With assert
you can simply write:
有了assert
可以简单的写:
assert(typeof "string" === "array")
assert(typeof "string" === "array")
In Javascript, there's no native assert
function, so you have to use one from some library.
在 Javascript 中,没有本机assert
函数,因此您必须使用某个库中的函数。
For simple introduction, you can check this article:
简单介绍,可以查看这篇文章:
http://fredkschott.com/post/2014/05/nodejs-testing-essentials/
http://fredkschott.com/post/2014/05/nodejs-testing-essentials/
I hope it helps.
我希望它有帮助。
回答by Karl.S
Previous answers can be improved in terms of performances and compatibility.
可以在性能和兼容性方面改进以前的答案。
Check onceif the Error
object exists, if not declare it :
检查一次,如果Error
对象存在,如果不声明它:
if (typeof Error === "undefined") {
Error = function(message) {
this.message = message;
};
Error.prototype.message = "";
}
Then, each assertion will check the condition, and alwaysthrow an Error
object
然后,每个断言都会检查条件,并且总是抛出一个Error
对象
function assert(condition, message) {
if (!condition) throw new Error(message || "Assertion failed");
}
Keep in mind that the console will not display the real error line number, but the line of the assert
function, which is not useful for debugging.
请记住,控制台不会显示真正的错误行号,而是显示assert
函数的行,这对调试没有用。