JavaScript-console的使用_016

JavaScript-console的使用

onsole 對象提供對瀏覽器控制檯的接入(如:Firefox 的 Web Console)。不同瀏覽器上它的工作方式是不一樣的,但這裏會介紹一些大都會提供的接口特性。

Console對象可以在任何全局對象中訪問,如 Window,WorkerGlobalScope 以及通過屬性工作臺提供的特殊定義。

它被瀏覽器定義爲 Window.console,也可被簡單的 console 調用。

方法

console.log()

console.log(obj1 [, obj2, ..., objN);
console.log(msg [, subst1, ..., substN);
console.log('String: %s, Int: %d,Float: %f, Object: %o', str, ints, floats, obj)
console.log(`temp的值爲: ${temp}`)

對於打印對象數據的時候要注意:
原來瀏覽器在打印對象的時候只是打印的一個對象快照信息,當你在控制檯點擊展開對象的時候,瀏覽器纔會去讀這個對象具體屬性,但是那個時候,這段代碼早就已經運行完了

類似出現這種,都爲null的情況:

SyntheticClipboardEvent {dispatchConfig: {…}, _targetInst: ReactDOMComponent, nativeEvent: ClipboardEvent, type: "paste", target: input, …}
bubbles: null
cancelable: null
clipboardData: null
currentTarget: null
defaultPrevented: null
dispatchConfig: null
eventPhase: null
isDefaultPrevented: null
isPropagationStopped: null
isTrusted: null
nativeEvent: null
target: null
timeStamp: null
type: null
_dispatchInstances: null
_dispatchListeners: null
_targetInst: null
__proto__: SyntheticEvent

 console.table()

這個方法需要一個必須參數 data,data 必須是一個數組或者是一個對象;還可以使用一個可選參數 columns。

clipboard.png

表格的第一列是 index。如果數據 data 是一個數組,那麼這一列的單元格的值就是數組的索引。 如果數據是一個對象,那麼它們的值就是各對象的屬性名稱。 注意(在 FireFox 中)console.table 被限制爲只顯示1000行(第一行是被標記的索引(原文:labeled index))。

clipboard.png

console.assert()

console.assert爲斷言輸出。第一個參數的表達式值爲false時,則打印輸出後面參數的值,否則爲 true,則無輸出並繼續執行程序。例如:

function notEqual(a, b) {
    console.assert(a === b, {
        msg: 'a is not equal b', 
        a: a,
        b: b
    });
}

// console.assert
notEqual({a: 1}, {a: 2});

console.time

你可以啓動一個計時器(timer)來跟蹤某一個操作的佔用時長。每一個計時器必須擁有唯一的名字,頁面中最多能同時運行10,000個計時器。當以此計時器名字爲參數調用 console.timeEnd() 時,瀏覽器將以毫秒爲單位,輸出對應計時器所經過的時間.

https://developer.mozilla.org...

https://www.jianshu.com/p/cf2...

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章