console 中的格式化打印(佔位符),和樣式定義

格式化打印

Gecko 9.0 (Firefox 9.0 / Thunderbird 9.0 / SeaMonkey 2.6) 首次發佈對string substitutions的支持.你能夠在傳遞給console的方法的時候使用下面的字符以期進行參數的替換。javascript

Substitution string Description
%o 打印javascript對象,能夠是整數、字符串以及JSON數據
%d or %i 打印整數
%s 打印字符串
%f 打印浮點數

當要替換的參數類型和預期的打印類型不一樣時,參數會被轉換成預期的打印類型。java

 
for (var i=0; i<5; i++) {
  console.log("Hello, %s. You've called me %d times.", "Bob", i+1);
}
console.log("I want to print a number:%d","string")

 

輸出樣例以下所示:git

 
[13:14:13.481] Hello, Bob. You've called me 1 times.
[13:14:13.483] Hello, Bob. You've called me 2 times.
[13:14:13.485] Hello, Bob. You've called me 3 times.
[13:14:13.487] Hello, Bob. You've called me 4 times.
[13:14:13.488] Hello, Bob. You've called me 5 times.
[13:14:13.489] I want to print a number:NaN

 

咱們發現"string"字符串被轉換成數字失敗成轉換成 [NaN en-US]github

爲console定義樣式

你能夠使用"%c"爲打印內容定義樣式:spa

console.log("%cMy stylish message", "color: red; font-style: italic");

 

相關文章
相關標籤/搜索