--- title: Console.assert() slug: Web/API/Console/assert tags: - console translation_of: Web/API/console/assert ---
如果断言为false,则将一个错误消息写入控制台。如果断言是 true,没有任何反应。
{{AvailableInWorkers}}
console.assert()方法在Node.js中的实现和浏览器中可用的console.assert()方法实现是不同的。在浏览器中当console.assert()方法接受到一个值为假断言的时候,会向控制台输出传入的内容,但是并不会中断代码的执行,而在Node.js v10.0.0之前,一个值为假的断言也将会导致一个AssertionError被抛出,使得代码执行被打断。v10.0.0修复了此差异,所以现在console.assert()在Node 和浏览器中执行行为相同 。
console.assert(assertion, obj1 [, obj2, ..., objN]); console.assert(assertion, msg [, subst1, ..., substN]); // c-like message formatting
assertionobj1 ... objNmsgsubst1 ... substN下面的代码示例演示了JavaScript对象的使用:
const errorMsg = 'the # is not even';
for (let number = 2; number <= 5; number += 1) {
console.log('the # is ' + number);
console.assert(number % 2 === 0, {number: number, errorMsg: errorMsg});
// 或者使用 ES2015 对象简写:
// console.assert(number % 2 === 0, {number, errorMsg});
}
// 输出:
// the # is 2
// the # is 3
// Assertion failed: {number: 3, errorMsg: "the # is not even"}
// the # is 4
// the # is 5
// Assertion failed: {number: 5, errorMsg: "the # is not even"}
请注意, 你可以在大多数浏览器中使用 console.log 进行格式化输出
console.log('the word is %s try number %d', 'foo', 123);
// 输出: the word is foo try number 123
但是 console.assert 在不同浏览器中可能获得不同的效果:
console.assert(false, 'the word is %s', 'foo'); // correct output in Node (e.g. v8.10.0) and some browsers // (e.g. Firefox v60.0.2): // Assertion failed: the word is foo // incorrect output in some browsers // (e.g. Chrome v67.0.3396.87): // Assertion failed: the word is %s foo
有关详细信息,请参阅 {{Domxref("console")}} 文档中的 输出文本到控制台。
| Specification | Status | Comment |
|---|---|---|
| {{SpecName("Console API", "#consoleassertexpression-object", "console.assert()")}} | {{Spec2("Console API")}} | Initial definition |
{{Compat("api.Console.assert")}}