Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我可以从另一个变量分配一个变量而不改变JavaScript中的值吗?_Javascript_Variables - Fatal编程技术网

我可以从另一个变量分配一个变量而不改变JavaScript中的值吗?

我可以从另一个变量分配一个变量而不改变JavaScript中的值吗?,javascript,variables,Javascript,Variables,我正在尝试使用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; e

我正在尝试使用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."
有没有办法在不改变第一个变量的情况下做同样的事情? 请保持简单。我5天前开始学习JavaScript。谢谢。

换衣服

let laterYears = myAge -= 2;

-=表示要更改myAge变量,然后将其分配给laterYears

感谢您让我们帮助您改变

let laterYears = myAge -= 2;

-=表示要更改myAge变量,然后将其分配给laterYears


感谢您让我们帮助您

-=
是作业操作员。您可以阅读有关赋值运算符的更多信息

laterYears=myAge-=2
laterYears=myAge=myAge-2
相同,后者将
myAge
的值递减2

因此,如果您不想更改此变量的值,我建议替换:

laterYears=myAge-=2
by
laterYears=myAge-2


祝你学习javascript好运

-=
是赋值运算符。您可以阅读有关赋值运算符的更多信息

laterYears=myAge-=2
laterYears=myAge=myAge-2
相同,后者将
myAge
的值递减2

因此,如果您不想更改此变量的值,我建议替换:

laterYears=myAge-=2
by
laterYears=myAge-2


祝你学习javascript好运

也许我不太明白,但我试过你
let laterYears=myAge-2停止使用运算符?它也有助于用
const
而不是
var
声明所有变量让laterYears=myAge你知道
-=
做什么吗?投票以打字错误结束。@AugustJelemson,他们不想改变
myAge
。。。这看起来像是一个打字错误。也许我没听懂,但我试过你
let laterYears=myAge-2停止使用运算符?它也有助于用
const
而不是
var
声明所有变量让laterYears=myAge你知道
-=
做什么吗?投票以打字错误结束。@AugustJelemson,他们不想改变
myAge
。。。看起来像是打字错误。