Console.assert()
console.assert()
は、アサーションが false になる場合に、コンソールへエラーメッセージを出力します。アサーションが true になる場合は、何も行いません。
注:
この機能は Web Worker 内で利用可能です。構文
console.assert(assertion, obj1 [, obj2, ..., objN]); console.assert(assertion, msg [, subst1, ..., substN]); // C ライクなメッセージ形式
引数
assertion
- 任意のブール式。アサーションが false になると、コンソールにメッセージを出力します。
obj1
...objN
- 出力する JavaScript オブジェクトのリスト。各オブジェクトを文字列で表現したものを、リストの並び順に追記して出力します。
msg
- 0 個以上の置換文字列を含む JavaScript 文字列。
subst1
...substN
msg
内の置換文字列を置き換える JavaScript オブジェクト。このパラメータで、出力形式を高度に制御できます。
Examples
下のコード例はオブジェクトをconsole.assert()
に渡す場合を示しています。
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 object property shorthand を使った版
// 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"}
置換文字列を含む文字列は、Node.jsや、大多数のブラウザではconsole.log
のパラメータとして動作することに注意してください
console.log('the word is %s', 'foo');
// 出力: the word is foo
このような文字列の使用は、現在のところ、すべてのブラウザでconsole.assert
のパラメータとして意図した通りには動作するわけではありません。
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
詳しくは console
のドキュメントで、コンソールにテキストを出力する をご覧ください。
仕様
仕様書 | 策定状況 | コメント |
---|---|---|
Console API console.assert() の定義 |
現行の標準 | 最初期の定義 |
ブラウザ実装状況
BCD tables only load in the browser