我正在嘗試制作這個功能,告訴我可以根據預算購買哪款吉他。我的問題是我創建了一個文字物件并且所有輸出都給出了相同的答案(條件一除外),因為我試圖訪問里面的屬性。
訪問具有專案名稱的屬性的最佳方法是什么?另外,請更正我使用的任何錯誤術語。
let instruments = {
guitar1: ["Gibson SG", "$3500"],
guitar2: ["Fender Strat", "$3000"],
guitar3: ["Ibanez JEM Custom", "$4200"],
};
function howMuchMoney() {
let money = prompt("What's your budget?");
if (money < 3000) {
alert("Broke");
} else if (money >= 3000) {
alert(`Buy the ${instruments.guitar1[0]}`);
} else if (money >= 3000) {
alert(`Buy the ${instruments.guitar2[0]}`);
} else if (money >= 4200) {
alert(`Buy the ${instruments.guitar3[0]}`);
}
}
howMuchMoney();
uj5u.com熱心網友回復:
您的程式有兩個主要問題:
prompt()回傳一個字串
prompt()回傳一個字串,但您想對數字進行比較,因此您需要先使用 . 將字串轉換為數字Number.parseFloat()。否則,您將只是根據詞典進行檢查,這可能會給您帶來意想不到的結果。
else ifs 的順序
您需要以實際上可以達到每個 else if 的方式安排 else if 陳述句,否則沒有必要定義其他情況,因為只能觸發一個。所以在使用的時候從多錢到少錢來排列<=。
只是一個評論:嘗試使用const而不是let每當您不更改幾乎總是(或應該)的值時。
const instruments = {
guitar1: ["Gibson SG", "$3500"],
guitar2: ["Fender Strat", "$3000"],
guitar3: ["Ibanez JEM Custom", "$4200"],
};
while (true) {
// we get a string here
const moneyStr = prompt(`What's your budget?\n(Enter "exit" to end program)`);
// end the inifinite loop if someone has entered "exit"
if (moneyStr === "exit" || moneyStr === null) break;
// parse the string to a float number
const money = Number.parseFloat(moneyStr);
// if the string cannot be parsed show error message and go to next iteration in loop meaning we ask for the input again
if (isNaN(money)) {
alert("Invalid input. Budget must be a number!");
continue;
}
// money is now a number
tellGuitar(money);
break;
}
/**
* Tell user which guitar to buy
* @param {number} money money the user has
*/
function tellGuitar(money) {
// broke first
if (money < 3000) {
alert("Broke");
// now go from most mones to least money as otherwise the other cases will never trigger
} else if (money >= 4200) {
alert(`Buy the ${instruments.guitar3[0]}`);
} else if (money >= 3500) {
alert(`Buy the ${instruments.guitar1[0]}`);
} else if (money >= 3000) {
alert(`Buy the ${instruments.guitar2[0]}`);
}
}
為簡單起見,當輸入無法轉換為數字的無效輸入時,我將程式包裝在無限回圈中。盡管存在無限回圈,但要退出程式,我添加了一個exit命令。按下時程式也將退出Cancel(即prompt()回傳null)。告訴用戶購買哪把吉他的實際邏輯被分解為另一種tellGuitar()以數字形式接收資金的方法。
uj5u.com熱心網友回復:
如果您的儀器陣列假設包含數百萬個儀器,您確實應該能夠支持假設情況。這樣,您就不會對任何值進行硬編碼。檢查此解決方案。
<button onclick="sendPrompt()">Click me</button>
<script>
const instruments = {
guitar1: ['Gibson SG', '$3500'],
guitar2: ['Fender Strat', '$3000'],
guitar3: ['Ibanez JEM Custom', '$4200'],
guitar4: ['Jimi Hendrix Golden Limited Edition', '$500000000']
};
const calculateInstrument = (instruments, money) => {
let bestOption = {
diff: null,
name: null,
};
for (const [name, price] of Object.values(instruments)) {
const parsed = price.slice(1);
const diff = money - parsed;
if (diff === 0) return name;
if ((bestOption.diff > diff && diff > 0) || diff > 0) bestOption = { name, diff };
}
return bestOption.name;
};
const sendPrompt = () => {
const val = prompt("What's your budget?");
if (!/^[0-9] $/.test(val)) return alert('Error! Only numbers!');
const name = calculateInstrument(instruments, val);
if (!name) return alert('You broke.')
alert(`You should buy ${name}`);
};
</script>
uj5u.com熱心網友回復:
我使用該map()方法為您提供了一個解決方案,該方法允許您遍歷所有密鑰,僅獲取價格與指定的 variable 預算匹配的那些密鑰money。
將結果輸出到console.
例如:
如果您將預算指定為$4000,您將獲得所有價值相等和價值較低的吉他的串列。
let instruments = {
guitar1: ["Gibson SG", "$3500"],
guitar2: ["Fender Strat", "$3000"],
guitar3: ["Ibanez JEM Custom", "$4200"],
};
function howMuchMoney() {
let money = prompt("What's your budget?");
Object.keys(instruments).map((key, index) => {
let price = instruments[key][1].replace("$", "");
if (price <= money) {
console.log(instruments[key][0]);
}
});
}
howMuchMoney();
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/463618.html
標籤:javascript 目的 特性
