LoginSignup
3
6

More than 5 years have passed since last update.

Chrome DevTool かんたんデバッグ機能 ~サーバーサイドでも抑えておきたい機能3選~

Last updated at Posted at 2018-05-10

JavaScript かんたんデバッグ機能3選

ChromeDevToolは機能が多くて全てを網羅するのが大変です。
しかし、その中の機能をほんの数個覚えるだけで、JavaScriptの大変なデバッグの時間が50%程削減されました。サーバーサイドが好きな人はconsole.logだけでゴリ押すことが多いイメージなので、特に覚えるのがかんたんで費用対効果のよかった以下の3つのデバッグ機能を紹介します。

①debugger;
②console.table([[Array, Array, Array]])
③console.trace()

対象読者

普段ひたすらconsole.logだけでデバッグしている人

サンプルコード

index.html

<!DOCTYPE html>
<html>
<head>
  <title></title>
</head>
<body>

<h1>HelloWorld</h1>
<form>
  <div>
    <label for="name">Name</label>
    <input type="text" name="name" class="input-field">
  </div>
  <div>
    <label for="age">Age</label>
    <input type="number" name="age" class="input-field">
  </div>
  <div>
    <label for="comment">Comment</label>
    <textarea name="comment" class="input-field"></textarea>
  </div>
  <div>
    <input type="submit" id="submit">
  </div>
</form>

<script src="app.js"></script>
</body>
</html>

samp.js
function fetchInputValue() {
  let inputs = document.querySelectorAll('.input-field')
  let aryForKeys = []
  let aryForValues = []

  debugger; // ①

  for (let input of inputs) {
    aryForKeys.push(input.name)
    aryForValues.push(input.value)
  }
  console.table([aryForKeys, aryForValues]) // ②
  console.trace() // ③
}

let submit = document.getElementById("submit")

submit.addEventListener("click", (e) => {
  e.preventDefault();
  fetchInputValue();
});

1. debugger;

JavaScriptコード内にDebuggerと記述すると、
そこでコードを止めてSourceパネルを開きます。
以下のgifのようにコードの実行順序 / 返り値 / 変数の値を追ったり、
sourceパネルでコードを書き換え保存して実行することもできます。

https://gyazo.com/0f53a0f6a70a2451cb65bedd809f954f

2. console.table

console.table([[1,2,3], [4,5,6]])
のように引数に二重配列を渡してあげるといい感じにテーブル表示してくれます。
APIの返り値チェックなどに非常に便利です。

https://gyazo.com/79d1d9e6d4be557a834c63c3b0cfb0d3

オブジェクトのテーブル表示も可能

配列でなく、JavaScriptオブジェクトであればプロパティを用いたテーブル表示も可能です。

引用元: 類似データ オブジェクトの比較  |  Tools for Web Developers  |  Google Developers

samp.js
function Person(firstName, lastName, age) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.age = age;
}

var family = {};
family.mother = new Person("Susan", "Doyle", 32);
family.father = new Person("John", "Doyle", 33);
family.daughter = new Person("Lily", "Doyle", 5);
family.son = new Person("Mike", "Doyle", 8);

console.table(family, ["firstName", "lastName", "age"]);

3. console.trace

console.traceを関数内に設置すると、
その関数がどこから呼ばれたかをトレースすることができます。
イベントが発火しているか、関数の実行タイミングは適正かなどをチェックすることができますね。

https://gyazo.com/074305f8f4de27ef4fbcd6d863afa885

参考文献

ひたすら公式を見ました。
Chrome DevTools  |  Tools for Web Developers  |  Google Developers

3
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
6