简体   繁体   English

JavaScript 访问文字 object 属性

[英]JavaScript Accessing literal object property

I'm trying to make this function that tells me which guitar I can purchased based on the budged.我正在尝试制作这个 function,它告诉我可以根据预算购买哪把吉他。 My issue is that I created a literal object and all outputs are giving the same answer (Except condition one) because I am trying to access the properties inside.我的问题是我创建了一个文字 object 并且所有输出都给出了相同的答案(条件一除外),因为我正在尝试访问其中的属性。

What would be the best way to access the property that has the name of the item?访问具有项目名称的属性的最佳方法是什么? Also, please correct any wrong terminology I use.另外,请更正我使用的任何错误术语。

 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();

There are two main issues with your program:您的程序有两个主要问题:

prompt() returns a string prompt()返回一个字符串

prompt() returns a string but you want to do comparisons on numbers so you need to convert the string to a number first using Number.parseFloat() . prompt()返回一个字符串,但您想对数字进行比较,因此您需要先使用Number.parseFloat()将字符串转换为数字。 Otherwise you will just be checking on a lexicographic basis which could potentially give you unexpected results.否则,您将只是按字典顺序进行检查,这可能会给您带来意想不到的结果。

Order of else if s else if的顺序

You need to arrange your else if statements in a way that every else if could actually be reached otherwise there is no point defining those other cases as only ever one can be triggered.你需要以一种方式安排你的 else if 语句,使得每一个 else if 都可以实际到达,否则定义那些其他情况是没有意义的,因为只有一个可以被触发。 So arrange them from most money to least money when using <= .因此,在使用<=时将它们从最多钱到最少钱排列。

Just a remark: Try to use const instead of let whenever you are not changing the value which is (or should be) almost always.只是一句话:每当您不更改几乎总是(或应该)的值时,请尝试使用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]}`); } }

For reason of simplicity I have wrapped the program in an infinite loop when an invalid input is entered that cannot be converted to a number.为简单起见,当输入无法转换为数字的无效输入时,我将程序包装在一个无限循环中。 To exit the program despite the infinite loop I have added an exit command.为了在无限循环中退出程序,我添加了一个exit命令。 The program will also exit when Cancel is pressed (ie prompt() returns null ).当按下Cancel时,程序也会退出(即prompt()返回null )。 The actual logic to tell the user which guitar to buy was factored out into another method tellGuitar() which receives the money as a number.告诉用户购买哪把吉他的实际逻辑被分解到另一个方法tellGuitar()中,该方法以数字形式接收钱。

You really should be able to support the hypothetical case of if your instruments array hypothetically contained millions of instruments.如果您的仪器阵列假设包含数百万个仪器,您真的应该能够支持假设情况。 That way, you won't hardcode any values.这样,您就不会硬编码任何值。 Check this solution.检查此解决方案。

 <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>

I made you a solution using the map() method, which allows you to go through all the keys, getting only those keys whose price matches the specified budget of variable money .我使用map()方法为您提供了一个解决方案,它允许您 go 通过所有密钥,仅获取价格与变量money的指定预算相匹配的那些密钥。

Output the result in the console . Output console中的结果。

For example:例如:

if you specify a budget as $4000 , you will get a list of all guitars of equal and lesser value.如果您将预算指定为$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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM