簡體   English   中英

如果 console.log(x) 正在注銷,為什么這會同時注銷?

[英]why does this log out both if console.log(x) is logging out?

我得到了這兩個輸出,但我不知道為什么

var sample = (x) =>  console.log(x) || x.slice(1); 
console.log(sample('jeff'));
// why does this log out both if console.log(x) is logging out?
// jeff
// eff

在此處輸入圖像描述

上面的undefinedconsole.log()的返回值。 這意味着

console.log(...) || 'here?'

將始終執行第二條語句,其中

console.log(...) && 'here?'

永遠不會。 這已經抓住了我幾次。 :\

可以這樣想(偽代碼):

function log(...arguments): void {
    for (argument of arguments)
        print argument

    // What do you return?
}

為了解釋 function 中發生了什么,當您將值“jeff”傳遞給 function 調用時,它會評估表達式console.log(x) || x.slice(1) console.log(x) || x.slice(1) ,它首先記錄"jeff"並且由於console.log()返回undefinedx.slice()被執行並返回"eff" 而且因為您已經將 function 調用包裝在另一個console.log()中,所以它最終將返回值“eff”記錄到控制台。

因此將兩個值記錄到控制台。

為了澄清嘗試使用瀏覽器中的開發工具在控制台中執行此操作

 console.log("hello") || console.log("hey")

 // expected result two logs in console "hello" and "hey"

現在嘗試在控制台中執行這個

 console.log("hello") && console.log("hey")

 // expected result only one log in console "hello"

在第二種情況下,這是因為第一個console.log被調用,它將“hello”記錄到控制台並返回undefined並且因為 undefined 是假的,所以第二個console.log永遠不會被調用。

暫無
暫無

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

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