[英]console.log(String(console.log('Not undefined')) === 'undefined'); console.log(String(console.log('Not undefined')) !== 'Not undefined');
console.log(String(console.log('Not undefined')) === 'undefined');
console.log(String(console.log('Not undefined')) !== 'Not undefined');
我覺得這兩行代碼應該給我錯誤的信息,但是?如果有人可以向我解釋?
讓我們將其划分為多個級別,以使此行為更清晰。 首先在第一行中執行最里面的命令:
console.log('Not undefined')
在這里, console.log
函數回顯"Not undefined"
但返回undefined
。 這是JavaScript 中所有函數的默認行為 。 如果它們未顯式返回某些內容,則它們將返回undefined
值。 從那里開始,我們一步一步地將undefined
強制轉換為帶有此行的string
:
String(console.log('Not undefined'))
如果我們結合先前的見解,JavaScript運行時將出現以下情況:
String(undefined)
這是對字符串"undefined"
求值。 接下來,您要進行字面比較( ===
比較值和類型 ),其結果為true
。
第二行是一樣的,只是你現在是比較String(console.log('Not undefined'))
是不是'Not undefined'
它是不是讓您得到true
為好。
事實上,確實如此。 如果在開發人員工具中運行代碼,則會注意到它返回三個輸出:未定義,“未定義”和“未定義”。 實際的未定義結果(不是字符串,它實際上是未定義的)來自console.log命令本身-雖然console.log能夠將輸出分別打印到控制台,但它本身會返回未定義的結果。 “未定義”字符串來自String函數,該函數似乎具有其自己的輸出(不確定原因)。 然后,您將獲得所需的結果-“未定義”。 因此,實際上,它確實將所需的字符串輸出到控制台,但是當您嘗試將代碼分配給變量時,如下所示:
var myVar = console.log(String(console.log('Not undefined')));
myVar返回未定義。 但是,它仍然將輸出打印到控制台。
console.log(String(console.log('Not undefined')) === 'undefined');
對於第一個,您可以從最深層次的調用中獲得: console.log('Not undefined')
,它顯然輸出Not undefined
。 然后將結果(不是控制台中實際的給定字符串)提供給String()
函數,該函數返回undefined
的字符串版本,即'undefined'
。 總而言之,與'undefined'
相比,它返回true
。
對於另一個,它幾乎是相同的:
console.log(String(console.log('Not undefined')) !== 'Not undefined');
在這里console.log('Not undefined')
只是將字符串記錄到控制台, 但是將 undefined
賦予String(),它將String轉換為"undefined"
。 然后與"Not undefined"
相比,兩者都是字符串,但是它們是不同的。 返回true
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.