为什么在 运行 时返回未定义?
Why is this returning undefined when run?
function switchBooks(book) {
book = "the book name";
}
var myBook = "new book";
myBook = switchBooks(myBook);
console.log(myBook)
我是 JS 新手,想了解为什么会这样?
进一步补充 UnholySheep 的评论。您需要 return 函数的结果以便稍后在您的代码中访问它。
The return statement ends function execution and specifies a value to
be returned to the function caller.
在你的例子中,函数调用者是 switchBooks(myBook);
function switchBooks(book) {
var book = "the book name";
return book; //This is the addition
}
var myBook = "new book";
myBook = switchBooks(myBook);
console.log(myBook)
您需要在函数内部添加return
。
function switchBooks(book) {
return book = "the book name";
}
var myBook = "new book";
myBook = switchBooks(myBook);
console.log(myBook)
function switchBooks(book) {
book = "the book name";
}
var myBook = "new book";
myBook = switchBooks(myBook);
console.log(myBook)
我是 JS 新手,想了解为什么会这样?
进一步补充 UnholySheep 的评论。您需要 return 函数的结果以便稍后在您的代码中访问它。
The return statement ends function execution and specifies a value to be returned to the function caller.
在你的例子中,函数调用者是 switchBooks(myBook);
function switchBooks(book) {
var book = "the book name";
return book; //This is the addition
}
var myBook = "new book";
myBook = switchBooks(myBook);
console.log(myBook)
您需要在函数内部添加return
。
function switchBooks(book) {
return book = "the book name";
}
var myBook = "new book";
myBook = switchBooks(myBook);
console.log(myBook)