目前,我的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);
}
});
}
}
那麼......目前,初始化程序被註釋掉了,所以'query === undefined' – theGleep
好的。在格式化問題時,我評論了這部分內容。我的實際代碼沒有被註釋掉。謝謝。 –
像這樣初始化'query':'query = process.argv [3] || 'Sign';'如果它具有一個值,或者如果它沒有值,則會分配'process.argv [3]'的值,分配一個默認字符串。這樣你可以省略'if .. else'構造。目前所描述的行爲僅僅是可能的,當'query'具有比空字符串更多的值時。請注意,「undefined」也是一個值。你檢查過該變量的值嗎? – Teemu