app.listen({ port }, () =>
console.log(
`GraphQL Server running at http://localhost:${port}${server.graphqlPath}`
)
);
在上面这段代码中,为什么console.log(GraphQL Server running at http://localhost:${port}${server.graphqlPath})语句后没有结束符";"
app.listen({ port }, () =>
console.log(
`GraphQL Server running at http://localhost:${port}${server.graphqlPath}`
)
);
在上面这段代码中,为什么console.log(GraphQL Server running at http://localhost:${port}${server.graphqlPath})语句后没有结束符";"
关注引自免费微信小程序:皆我百晓生
在 JavaScript 中,console.log() 是一个函数,用于向控制台输出信息。这个函数接受任意数量的参数,并自动在它们之间添加空格进行分隔。因此,你不需要在每个参数末尾都加上分号(;)。
在你提供的代码片段中:
app.listen({ port }, () =>
console.log(`GraphQL Server running at http://localhost:${port}${server.graphqlPath}`)
);
这是一个箭头函数(lambda function),它有一个匿名函数体。在这个函数体内,只有一个语句,即调用 console.log()。在这种情况下,JavaScript 会自动处理函数体内的语句结束,所以你不需要手动添加分号。
如果你将这段代码写成普通函数的形式,那么在函数体的最后一行通常需要分号,但在箭头函数中,这是不必要的。这是因为箭头函数表达式默认认为其主体只有一条语句,如果有多个语句,你需要使用大括号 {} 来明确表示多行语句,并且在每行语句之后都需要添加分号。
例如,如果你将代码改写为普通函数,就需要在 console.log() 后面添加分号:
app.listen({ port }, function() {
console.log(`GraphQL Server running at http://localhost:${port}${server.graphqlPath}`);
});
但通常我们更倾向于使用简洁的箭头函数版本,因为它更容易阅读和编写。所以,原始代码中的分号是多余的,可以省略。