console.assert() - Web APIs 编辑

The console.assert() method writes an error message to the console if the assertion is false. If the assertion is true, nothing happens.

Note:

This feature is available in Web Workers.

Syntax

console.assert(assertion, obj1 [, obj2, ..., objN]);
console.assert(assertion, msg [, subst1, ..., substN]); // C-like message formatting

Parameters

assertion
Any boolean expression. If the assertion is false, the message is written to the console.
obj1 ... objN
A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output.
msg
A JavaScript string containing zero or more substitution strings.
subst1 ... substN
JavaScript objects with which to replace substitution strings within msg. This parameter gives you additional control over the format of the output.

Examples

The following code example demonstrates the use of a JavaScript object following the assertion:

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});
    // or, using ES2015 object property shorthand:
    // console.assert(number % 2 === 0, {number, errorMsg});
}
// output:
// 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"}

Note that, while a string containing a substitution string works as a parameter for console.log in Node and many, if not most, browsers...

console.log('the word is %s', 'foo');
// output: the word is foo

...the use of such a string does not currently work as intended as a parameter for console.assert in all browsers:

console.assert(false, 'the word is %s', 'foo');
// correct output in Node.js 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

See Outputting text to the console in the documentation of console for further details.

Specifications

SpecificationStatusComment
Console API
The definition of 'console.assert()' in that specification.
Living StandardInitial definition

Browser compatibility

BCD tables only load in the browser

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:118 次

字数:3951

最后编辑:7 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文