JavaScript调试技巧

快速寻找DOM元素

JavaScript调试技巧_第1张图片
DOM elements

以表格的形式显示数据对象

var animals = [
 { animal: 'Horse', name: 'Henry', age: 43 },
 { animal: 'Dog', name: 'Fred', age: 13 },
 { animal: 'Cat', name: 'Frodo', age: 18 }
];
console.table(animals);

将输出......

JavaScript调试技巧_第2张图片
Console.table

得到一个函数的堆栈轨迹(某个时间的调用堆栈状态)

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();

将输出......

JavaScript调试技巧_第3张图片
CONSOLE TRACE

在复杂的调试中发现重要信息

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');

在上述代码中 %s 应用于字符串, %i 应用于整型 %c 应用于CSS样式.
将输出......

JavaScript调试技巧_第4张图片
Custom console message

你可能感兴趣的:(JavaScript调试技巧)