2017-10-20 37 views
-1

目前,我的if/else語句無法正常工作,因爲它永遠不會到我的代碼的其他部分。節點應用程序接受一個參數(process.argv [3])並使用它來選擇要調用的API。 process.argv [4]用於指定要搜索的內容(例如「Yesterday」),並在提供參數時正常工作。但是,如果用戶將該參數留空,我想要進行默認搜索。我不確定爲什麼它永遠不會進入代碼的其他部分。當用戶沒有指定搜索參數時,node.js代碼不會讀取else條件(只有條件時讀取)

我是新來的編程,所以我敢肯定這是我的錯誤,但我已經嘗試重寫聲明和相同的問題。任何幫助將不勝感激。

function getSpotifySongInfo() { 
     //4th node argument is reserved for the song user wants to select 
     var query = process.argv[3]; 
     if (query !== "") { 
      //could make this less repeating code by passing the song as a parameter? 
      spotifyClient.search({ type: 'track', query: query, limit: 1 }, function (err, data) { 
       if (!err) { 
        console.log("=============Artist==Track==Album==PreviewURL============================="); 
        console.log("Artist: " + data.tracks.items[0].artists[0].name); 
        console.log("Track: " + data.tracks.items[0].name); 
        console.log("Album: " + data.tracks.items[0].name); 
        console.log("Preview URL: " + data.tracks.items[0].preview_url); 
       } else { 
        console.log(err); 
       } 
      }); 

     } else { 
      //need to make this specific for Ace of Base. For some reason it's not changing the query to reflect default song. I've tried commenting this portion out and just testing w/ a simple console.log("test") and nothing... 
      query = 'The Sign'; 
      spotifyClient.search({ type: 'track', query: query, limit: 1 }, function (err, data) { 
       if (!err) { 
        console.log("=============Artist==Track==Album==PreviewURL============================="); 
        console.log("Artist: " + data.tracks.items[0].artists[0].name); 
        console.log("Track: " + data.tracks.items[0].name); 
        console.log("Album: " + data.tracks.items[0].name); 
        console.log("Preview URL: " + data.tracks.items[0].preview_url); 
       } else { 
        console.log(err); 
       } 
      }); 
     } 
    } 
+1

那麼......目前,初始化程序被註釋掉了,所以'query === undefined' – theGleep

+0

好的。在格式化問題時,我評論了這部分內容。我的實際代碼沒有被註釋掉。謝謝。 –

+0

像這樣初始化'query':'query = process.argv [3] || 'Sign';'如果它具有一個值,或者如果它沒有值,則會分配'process.argv [3]'的值,分配一個默認字符串。這樣你可以省略'if .. else'構造。目前所描述的行爲僅僅是可能的,當'query'具有比空字符串更多的值時。請注意,「undefined」也是一個值。你檢查過該變量的值嗎? – Teemu

回答

0

if (query !== "")是一個不好的測試,可能不會做你想做的。例如:

var query = undefined; 
query !== "" 
// true 

query = null 
query !== "" 
// true 

您正在測試一個非常具體的東西 - 一個空字符串 - 這你可能沒有得到作爲參數傳遞給你的函數。

導致少量代碼的更好方法是將值分配給query(如果不存在)。你可以這樣做:

if (!query) { 
    query = 'The Sign' 
} 

然後你根本不需要if/else的代碼。一個快速簡便的方法來做到這一點是:

var query = process.argv[3] || 'The Sign' 

,這樣就會將指定的process.argv[3]值,或者,如果該值是falsy,你將得到默認。這是Javascript中非常常見的模式。

+0

非常感謝您的詳細解釋。現在你已經解釋了這一點,這很有道理,但我對JavaScript的理解顯然並不完整。感謝你的幫助,並教我一些東西。 –