人们为什么在某些情况下会使用变量? [英] Why do people use variables in some cases?
问题描述
我知道这个问题的标题看起来很吓人,但事实并非如此.抱歉!
I know this question title looks scary, but it isn't. Sorry!
好吧,创建一次性的/不变的变量"有什么意义?
Ok, so, what's the point of creating a one-time-only/unchangeable "variable"?
让我们说我在Person对象中有一个名为"name"的属性.
Lets say I have one property called "name" in a Person object.
const Person = {
name: 'Luis Felipe Zaguini'
};
好的.因此,经常看到人们这样做:
Alright. So, it's incredibly common to see people doing this:
let personName = Person.name;
console.log(`I've written my name, and it is ${personName}.`);
就是这样.在大多数情况下,该变量仅使用一次.或者,有时,它在其他语句中被引用,但是您知道,它没有用,因为有一种无需设置新变量即可引用它的方法.
And that's it. In the majority of times that variable is used only once. Or, sometimes, it's referenced in other statements, but you know, it's useless because there IS a way to reference it without setting a new variable.
通常,您正在浪费CPU内存,将内存分配给无用的东西,因为实际上您可以多次键入Person.name
并执行以下操作:
Tecnically, you're wasting CPU memory, allocating memory for something useless because you can, in fact, type Person.name
multiple times, and do this:
console.log(`I've written my name, and it is ${Person.name}.`);
此外,您还浪费时间,在代码中添加了更多行.我太劳累了吗?很多程序员都在做这种事情,但是就我个人而言,这似乎不太适合.
Also, you're wasting time and adding more lines to your code. Am I overracting? Lot of programmers do this kind of stuff, but personally it doesn't seem to fit very well to me.
推荐答案
有多种原因
-
'const`变量将防止该值意外更改,例如如果您编写了 closure ,其中包含在直接作用域之外可以访问的变量.
A 'const` variable will prevent the value from accidentally changing, e.g. if you have written a closure that includes a variable that is accessible outside immediate scope.
JavaScript引擎尚不能常见的子表达式消除,这是一种非常常见的编译器优化.使用临时变量可以提高性能,例如在此示例中.
Javascript engines are not yet capable of common subexpression elimination, which is a very common compiler optimization. Using a temporary variable could improve performance, like in this example.
有时,使用不同名称的变量可以阐明功能;请参见编写真正明显的代码(ROC).示例:
Sometimes a variable with a different name can clarify the functionality; see Writing Really Obvious Code (ROC). Example:
var activeUsername = User.name; //It's not just a user's name, it's the active user's name!
有时,额外的变量使调试/监视变量更加容易
Sometimes that extra variable makes it easier to debug/watch variables
有时候您想在分配过程中设置一个单独的断点
Sometimes you want to set a separate breakpoint during the assignment
我锻炼过度吗?
Am I overracting?
是的
这篇关于人们为什么在某些情况下会使用变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!