我正在嘗試使用帶有 if 陳述句的方法來測驗物件是否具有特定鍵的值。
function PCParts(motherboard, graphics, cpu, randomAccessMemory) {
this.motherboard = motherboard;
this.graphics = graphics;
this.cpu = cpu;
this.randomAccessMemory = randomAccessMemory;
//these methods are called and a result is displayed
this.caseSize = case_size();
this.storage = storage_device();
}
//this should check the input and return a proper case size.
//For some reason, in the for-in loop it decides to return "mid-tower" regardless of if the first part of the if statement is true.
function case_size() {
if (this.motherboard == "MSI B450 Tomahawk") {
this.caseSize = "full tower";
} else {
this.caseSize = "mid tower";
}
return this.caseSize;
}
//this is having the same issue as case_size function
//it refuses to display "NVMe-1TB" even if the if statment is true.
//I tried removing "this" to see if that was the issue and it refused to display anything.
function storage_device() {
if (this.cpu == "AMD Ryzen 5" && this.randomAccessMemory == "Corsair Vengeance 32GB") {
this.storage = "NVMe 1TB";
} else {
this.storage = "HDD 1TB";
}
return this.storage;
}
let gaming_computer = new PCParts("MSI B450 Tomahawk", "GTX 3090", "AMD Ryzen 5", "Corsair Vengeance 32GB");
for (let property in gaming_computer) {
document.write(`${property}: ${gaming_computer[property]} <br>`);
}
代碼用我遇到的問題進行了注釋,但基本上“if”陳述句由于某種原因是錯誤的,而“else”陳述句就是正在顯示的內容。
是否有一些物件方法可以針對字串測驗新物件值?如果這已在其他地方得到回答,對不起......我一直在尋找但找不到答案。謝謝。
uj5u.com熱心網友回復:
在您的 case_size 中,您使用了這個關鍵字。但 case_size 只是一個函式而不是一個類。所以這個關鍵字不應該被使用。而在 PCParts() 中,當您呼叫 case_size() 時,您必須傳遞主板的引數,以便在自己的函式中它可以訪問主板的值,否則它不能從另一個函式中獲取主板的值。就這樣 。快樂編碼!
function PCParts(motherboard, graphics, cpu, randomAccessMemory) {
this.motherboard = motherboard;
this.graphics = graphics;
this.cpu = cpu;
this.randomAccessMemory = randomAccessMemory;
this.caseSize = case_size(motherboard);
this.storage = storage_device();
}
function case_size(motherboard) {
if (motherboard == "MSI B450 Tomahawk") {
caseSize = "full tower";
} else {
caseSize = "mid tower";
}
return caseSize;
}
function storage_device() {
if (this.cpu == "AMD Ryzen 5" && this.randomAccessMemory == "Corsair Vengeance 32GB") {
this.storage = "NVMe 1TB";
} else {
this.storage = "HDD 1TB";
}
return this.storage;
}
let gaming_computer = new PCParts("MSI B450 Tomahawk", "GTX 3090", "AMD Ryzen 5", "Corsair Vengeance 32GB");
for (let property in gaming_computer) {
document.write(`${property}: ${gaming_computer[property]} <br>`);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/513783.html
上一篇:Docker容器無法通過apt安裝任何軟體包,之前使用aptupdate
下一篇:條件回圈重復列印錯誤輸出
