--- title: Console.assert() slug: Web/API/console/assert tags: - API - DOM - Debugging - Method - NeedsBrowserCompatibility - Web Development - console - web console translation_of: Web/API/console/assert ---
console.assert() は、アサーションが false になる場合に、コンソールへエラーメッセージを出力します。アサーションが true になる場合は、何も行いません。
{{AvailableInWorkers}}
console.assert(assertion, obj1 [, obj2, ..., objN]); console.assert(assertion, msg [, subst1, ..., substN]); // C ライクなメッセージ形式
assertionobj1 ... objNmsgsubst1 ... substNmsg 内の置換文字列を置き換える JavaScript オブジェクト。このパラメータで、出力形式を高度に制御できます。下のコード例はオブジェクトを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
詳しくは {{domxref("console")}} のドキュメントで、コンソールにテキストを出力する をご覧ください。
| 仕様書 | 策定状況 | コメント |
|---|---|---|
| {{SpecName("Console API", "#assert", "console.assert()")}} | {{Spec2("Console API")}} | 最初期の定義 |
{{Compat("api.Console.assert")}}