2017-10-20 126 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的理解显然并不完整。感谢你的帮助,并教我一些东西。 –

相关问题