這個問題在這里已經有了答案: 在 JS 中回傳多個值 [重復] (2 個回答) 在 JavaScript 中回傳多個值? (20 個回答) 3 小時前關閉。
我正在學習物件和建構式,因此為一本書創建了一個物件。
在使用一個元素(書籍或作者或頁面或閱讀)進行一些測驗后,它可以正常作業,但是當我添加超過 1 個元素時,它只回傳最終值。
例如,下面的內容僅"nope"在我希望它回傳title, author, pages, read(正如我認為我的函式"bookInfo"宣告的那樣?
我在這里遺漏了什么,因為我已經根據一些示例檢查了我的代碼并且看不到任何問題?
function Book(title, author, pages, read) {
this.title = title
this.author = author
this.pages = pages
this.read = read
this.bookInfo = function() {
return (title, author, pages, read)
}
}
const LOTR = new Book('lord of the rings', 'JRR', '366', 'nope');
console.log(LOTR.bookInfo());
// should print 'lord of the rings', 'JRR', '366', 'nope') but only returns 'nope' (or whatever the last value is?)
uj5u.com熱心網友回復:
您可以在陣列中回傳分配的值:
this.bookInfo = function() {
return [this.title, this.author, this.pages, this.read];
}
或物件:
this.bookInfo = function() {
return {title:this.title, author:this.author, pages:this.pages, read:this.read};
}
或字串:
this.bookInfo = function() {
return `${this.title} ${this.author} ${this.pages} ${this.read}`;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/365183.html
標籤:javascript
上一篇:呼叫一組JS代碼而不是另一組
