目前,我的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