簡體   English   中英

console.log 的奇怪問題

[英]Strange issue with console.log

const myFather = {
  name: 'John',
  age: 78,
  getDetails: function () {
    return 'The name of my father is ' + this.name + ' and he is ' + this.age + ' old.'
  }
}

如果我運行以下代碼行,我會得到預期的結果:

console.log(myFather.__proto__ === Object.prototype)

如果我運行它,我會按預期得到文本:

console.log('myFather.__proto__ === Object.prototype:')

但是如果我運行它,我只會得到錯誤的結果。 甚至沒有文字顯示:

console.log('myFather.__proto__ === Object.prototype:' + myFather.__proto__ === Object.prototype)

我不明白為什么?

你實際上是在這樣做:

console.log( ('myFather.__proto__ === Object.prototype:' + myFather.__proto__) === Object.prototype);

所以這個等式的結果是false

聽起來像是運算符優先級的情況? 如果您將第二部分包裹在括號中,它是否有效,例如

console.log('myFather.__proto__ === Object.prototype:' + (myFather.__proto__ === Object.prototype))

運算符優先級,如MDN或其他 JS 核心文檔中所述,定義了計算運算符的順序。 在大多數情況下,這個列表並不那么有趣,因為一個語句中的簡單賦值可能不會使用多個不同的運算符。 但在您的情況下,有一個+運算符和===運算符。 加法運算符的優先級高於相等運算符,這意味着:首先計算它。 因此,這些是您的日志調用的內部步驟,逐行:

console.log('myFather.__proto__ === Object.prototype:' + myFather.__proto__ === Object.prototype)

console.log('myFather.__proto__ === Object.prototype:[object Object]' === Object.prototype)

console.log(false)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM