JavaScript调试技巧之console.log()
与alert()函数类似,console.log()也可以接受变量并将其与别的字符串进行拼接:
代码如下:
//Use variable
var name = "Bob";
console.log("The name is: " + name);
var name = "Bob";
console.log("The name is: " + name);
(注意如上console.log中的name是不用双引号的)
与alert()函数不同的是,console.log()还可以接受变量作为参数传递到字符串中,其具体语法与C语言中的printf语法一致:
代码如下:
//Use parameter
var people = "Alex";
var years = 42;
console.log("%s is %d years old.", people, years);
var people = "Alex";
var years = 42;
console.log("%s is %d years old.", people, years);
上述代码的执行结果为:”Alex is 42 years old.”