JavaScript 開發上的小技巧

前端開發的小技巧

debugger

除了console.log、console.dir,也可以在語句上加入debugger,Browser執行到這行代碼的時候,會自動立即停止。

1
2
3
if (thisThing) {
debugger;
}

將objects顯示為表格

console.table可以將objects的對象展開成一個table,方便看清楚資料的內容

使用 console.time() 和 console.timeEnd()來查看loop耗時

1
2
3
4
5
6
7
8
9
console.time('Start');

var items = [];

for (var i = 0; i < 10000; i++) {
items.push({index:i});
}

console.timeEnd();

console.trace 來追蹤函數的調用過程

可以清楚知道函數的被調用過程清楚的呈現到開發者工具上

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
var car; 
var func1 = function() {
func2();
}
var func2 = function() {
func4();
}
var func3 = function() {
}
var func4 = function() {
car = new Car();
car.funcX();
}
var Car = function() {
this.brand = 'volvo';
this.color = 'red';
this.funcX = function() {
this.funcY();
}
this.funcY = function() {
this.funcZ();
}
this.funcZ = function() {
console.trace('trace car');
}
}
func1();

自己寫console.log出來的訊息樣式

目前已知的有console.logconsole.debugconsole.warnconsole.infoconsole.error 等等。也可自己美化自訂這些功能。

1
2
3
4
5
6
7
8
9
10
console.todo = function(msg) {
console.log('%c %s %s %s', 'color: yellow; background-color: black;', '–', msg, '–');
}

console.important = function(msg) {
console.log('%c %s %s %s', 'color: brown; font-weight: bold; text - decoration: underline;', '–', msg, '–');
}

console.todo('This is something that’ s need to be fixed');
console.important('This is an important message');

在console.log中 可以用 %s 設置字串,%i設置數字,%c設置樣式

查看特定函數的調用參數

1
2
3
4
5
6
7
var func1 = function (x, y, z) {
//todo...
}

monitor(func1);
func1(1,2);
// -> function func1 called with arguments: 1, 2

參考原文

The 14 JavaScript debugging tips you probably didn’t know
Chrome 开发者工具中文文档

0%