我正在尝试使用 JavaScript 编写一个狗年计算器。它需要输入年龄,进行数学计算并输出一个以狗岁为单位的年龄字符串。我遇到麻烦了。我不知道如何在不更改用户输入的年龄的情况下提取年龄数字并进行数学计算。
//Creating a variable with my age
let myAge = 37;
//The first two years of a dog’s life count as 10.5 dog years each. This is the math
let earlyYears = 2;
earlyYears *= 10.5;
//Each year following the first 2 equates to 4 dog years.
let laterYears = myAge -= 2; //This is the problem line - how can I do this without changing myAge?
laterYears *= 4;
// Combine the two numbers for my age in dog years.
myAgeInDogYears = laterYears + earlyYears;
//Hi, my name is:
let myName = "Dwayne".toLowerCase();
console.log(`My name is ${myName}. I am ${myAge} years old in human years which is ${myAgeInDogYears} years old in dog years.`);
//output is "My name is dwayne. I am 35 years old in human years which is 161 years old in dog years."
有没有办法在不改变第一个变量的情况下做同样的事情? 请保持简单。我五天前开始学习 JavaScript。谢谢。
最佳答案
改变
let laterYears = myAge -= 2;
至
let laterYears = myAge - 2;
-= 表示您要更改 myAge 变量,然后将其分配给laterYears
感谢您让我们为您提供帮助
关于javascript - 我可以从另一个变量分配一个变量而不更改 JavaScript 中的值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60366178/